import 'server-only'

import { NextResponse, type NextRequest } from 'next/server'
import { getSessionUser } from '@/lib/auth'
import { canAccessSurface } from '@/lib/domain/moderator-access'
import type { BoardActor } from '@/lib/data/dev-tasks'
import { verifyBoardKey } from '@/lib/integrations/dev-task-keys'

export type ActorResult = { ok: true; actor: BoardActor } | { ok: false; response: NextResponse }

/**
 * Board API caller (CTO chat, another project): a bearer board key whose
 * SHA-256 is in DEV_TASKS_API_KEY_HASHES. X-Task-Source names the caller in
 * the history ("HHA Workspace CTO", "HHA Brain CTO"); it is a label, not
 * a credential.
 */
export function apiActor(req: NextRequest): ActorResult {
  if (!verifyBoardKey(req.headers.get('authorization'), process.env.DEV_TASKS_API_KEY_HASHES)) {
    return { ok: false, response: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) }
  }
  const label = (req.headers.get('x-task-source') ?? '').replace(/[^\w .,()&/-]/g, '').trim().slice(0, 60) || 'HHA Workspace CTO'
  return { ok: true, actor: { kind: 'api', label, role: 'manager' } }
}

/** A signed-in person on the board page: the platform admin manages, a granted developer moves tasks. */
export async function sessionActor(): Promise<ActorResult> {
  const user = await getSessionUser()
  if (!user) return { ok: false, response: NextResponse.json({ error: 'Sign in first.' }, { status: 401 }) }
  if (!canAccessSurface(user, 'dev_tasks')) return { ok: false, response: NextResponse.json({ error: 'You do not have access to this page.' }, { status: 403 }) }
  const admin = user.role === 'admin'
  return { ok: true, actor: { kind: admin ? 'admin' : 'developer', label: user.name || user.email, role: admin ? 'manager' : 'developer' } }
}

export function noStore(body: unknown, status = 200): NextResponse {
  const res = NextResponse.json(body, { status })
  res.headers.set('Cache-Control', 'no-store')
  return res
}
