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'
import crypto from 'crypto'

export async function GET() {
  let user
  try { user = await requireUser() } catch (err) { if (isAuthError(err)) return err; throw err }
  const agents = agentRepo.listByUser(user.id)

  // Attach skill IDs to each agent
  const result = agents.map((agent) => ({
    ...agent,
    skillIds: agentSkillRepo.listSkillIdsByAgent(agent.id),
  }))

  return NextResponse.json(result)
}

export async function POST(req: Request) {
  let user
  try { user = await requireUser() } catch (err) { if (isAuthError(err)) return err; throw err }
  const body = await req.json()
  const id = crypto.randomUUID()

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

  return NextResponse.json({ ...agent, skillIds: [] }, { status: 201 })
}
