import { NextRequest, NextResponse } from 'next/server'
import { readFile, appendFile, mkdir } from 'fs/promises'
import { dirname } from 'path'

const CEO_PIN = process.env.CEO_PIN || '5050'
const COUNCIL_PATH = '/home/ccuser/the-50-dollar-app/data/control-centre-council.jsonl'
const MAX_MESSAGE_LENGTH = 2000

interface CouncilEntry {
  id: string
  ts: string
  author: string
  message: string
}

function isAuthorized(pin: string | null): boolean {
  return pin === CEO_PIN
}

async function readCouncil(): Promise<CouncilEntry[]> {
  try {
    const raw = await readFile(COUNCIL_PATH, 'utf8')
    return raw
      .split('\n')
      .filter(Boolean)
      .map((line) => {
        try {
          return JSON.parse(line) as CouncilEntry
        } catch {
          return null
        }
      })
      .filter((entry): entry is CouncilEntry => Boolean(entry))
      .slice(-200)
      .sort((a, b) => new Date(a.ts).getTime() - new Date(b.ts).getTime())
  } catch {
    return []
  }
}

export async function GET(request: NextRequest) {
  const pin = request.nextUrl.searchParams.get('pin')
  if (!isAuthorized(pin)) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })

  const messages = await readCouncil()
  return NextResponse.json({ messages })
}

export async function POST(request: NextRequest) {
  let body: { pin?: string; message?: string; author?: string } = {}

  try {
    body = await request.json()
  } catch {
    return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })
  }

  if (!isAuthorized(body.pin || null)) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })

  const message = (body.message || '').trim()
  const author = (body.author || 'operator').trim() || 'operator'

  if (!message) return NextResponse.json({ error: 'Message is required' }, { status: 400 })
  if (message.length > MAX_MESSAGE_LENGTH) {
    return NextResponse.json({ error: `Message too long (max ${MAX_MESSAGE_LENGTH} chars)` }, { status: 400 })
  }

  const entry: CouncilEntry = {
    id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
    ts: new Date().toISOString(),
    author: author.slice(0, 50),
    message,
  }

  try {
    await mkdir(dirname(COUNCIL_PATH), { recursive: true })
    await appendFile(COUNCIL_PATH, `${JSON.stringify(entry)}\n`, 'utf8')
    return NextResponse.json({ ok: true, message: entry })
  } catch {
    return NextResponse.json({ error: 'Failed to save message' }, { status: 500 })
  }
}
