import { NextResponse } from 'next/server'
import { agentRepo } from '@/lib/database/repositories/agent.repo'
import { agentSkillRepo } from '@/lib/database/repositories/agent-skill.repo'
import { isAuthError, requireUser } from '@/lib/auth/session'

export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) {
  let user
  try { user = await requireUser() } catch (err) { if (isAuthError(err)) return err; throw err }
  const { id } = await params
  const agent = agentRepo.findByIdAndUser(id, user.id)
  if (!agent) return NextResponse.json({ error: 'Not found' }, { status: 404 })

  const skillIds = agentSkillRepo.listSkillIdsByAgent(id)
  return NextResponse.json({ ...agent, skillIds })
}

export async function PATCH(req: Request, { params }: { params: Promise<{ id: string }> }) {
  let user
  try { user = await requireUser() } catch (err) { if (isAuthError(err)) return err; throw err }
  const { id } = await params
  const body = await req.json()
  const hasUpdate =
    body.name !== undefined ||
    body.description !== undefined ||
    body.model !== undefined ||
    body.permission_mode !== undefined ||
    body.is_main !== undefined ||
    body.parent_id !== undefined ||
    body.enabled !== undefined ||
    body.instructions !== undefined ||
    body.soul !== undefined ||
    body.identity !== undefined ||
    body.tools_config !== undefined
  if (!hasUpdate) {
    return NextResponse.json({ error: 'No fields to update' }, { status: 400 })
  }

  const agent = agentRepo.updateFields(id, user.id, {
    ...(body.name !== undefined && { name: body.name }),
    ...(body.description !== undefined && { description: body.description }),
    ...(body.model !== undefined && { model: body.model }),
    ...(body.permission_mode !== undefined && { permissionMode: body.permission_mode }),
    ...(body.is_main !== undefined && { isMain: body.is_main ? 1 : 0 }),
    ...(body.parent_id !== undefined && { parentId: body.parent_id }),
    ...(body.enabled !== undefined && { enabled: body.enabled ? 1 : 0 }),
    ...(body.instructions !== undefined && { instructions: body.instructions }),
    ...(body.soul !== undefined && { soul: body.soul }),
    ...(body.identity !== undefined && { identity: body.identity }),
    ...(body.tools_config !== undefined && {
      toolsConfig: typeof body.tools_config === 'string' ? body.tools_config : JSON.stringify(body.tools_config),
    }),
  })

  if (!agent) return NextResponse.json({ error: 'Not found' }, { status: 404 })
  const skillIds = agentSkillRepo.listSkillIdsByAgent(id)
  return NextResponse.json({ ...agent, skillIds })
}

export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) {
  let user
  try { user = await requireUser() } catch (err) { if (isAuthError(err)) return err; throw err }
  const { id } = await params
  agentRepo.deleteById(id, user.id)
  return NextResponse.json({ ok: true })
}
