import { AUDIT_ACTIONS, writeAudit } from '@/lib/audit'
import { apiRoute } from '@/lib/api/handler'
import { copilotSchema, type CopilotInput } from '@/lib/api/schemas'
import { getLocale } from '@/lib/i18n/server'
import { answerQuestion } from '@/lib/services/copilot-service'

export const dynamic = 'force-dynamic'

/**
 * Copilot endpoint.
 *
 * The question is audited but the answer is not stored: it is a view over data the user
 * could already reach, and keeping a transcript of every operator query would be a
 * privacy cost with no operational benefit.
 */
export const POST = apiRoute<Record<string, string>, CopilotInput>(
  { permission: 'copilot.use', bodySchema: copilotSchema, limit: 60 },
  async ({ body, user, request }) => {
    const locale = await getLocale()
    const answer = await answerQuestion(body.question, user, locale)

    await writeAudit({
      action: AUDIT_ACTIONS.copilotQuery,
      entity: 'copilot',
      user,
      request,
      detail: `intent=${answer.intent}`,
      status: answer.permissionDenied ? 'denied' : 'success',
    })

    return answer
  },
)
