import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { requireCompanyAdminContext } from '@/lib/api-guard'
import { publicOrigin } from '@/lib/app-url'
import { loadRule, ruleOperation, toViews } from '@/lib/data/auto-participant-rules'

const schema = z.object({
  op: z.enum(['disable', 'reactivate', 'remove', 'cancel', 'resend', 'change_scope']),
  scope_type: z.string().optional().nullable(),
  company_id: z.string().uuid().optional().nullable(),
})

/** Manage one company rule (Task 7.4): the rule must belong to the active company. */
export async function POST(req: NextRequest, ctx: { params: Promise<{ ruleId: string }> }) {
  const { ruleId } = await ctx.params
  const parsed = schema.safeParse(await req.json().catch(() => ({})))
  if (!parsed.success) return NextResponse.json({ error: 'Unknown operation.' }, { status: 400 })
  const guard = await requireCompanyAdminContext({ companyId: parsed.data.company_id })
  if (!guard.ok) return guard.response
  const rule = await loadRule(ruleId)
  if (!rule || rule.rule_type !== 'company' || rule.owner_company_id !== guard.companyId) {
    return NextResponse.json({ error: 'Rule not found.' }, { status: 404 })
  }
  const res = await ruleOperation({
    actor: guard.user, rule, op: parsed.data.op, scope_type: parsed.data.scope_type,
    companyName: guard.company.display_name || guard.company.legal_name, origin: publicOrigin(req),
  })
  if (!res.ok) return NextResponse.json({ error: res.error }, { status: res.status ?? 400 })
  const [view] = await toViews([res.rule])
  return NextResponse.json({ ok: true, rule: view })
}
