/**
 * PATCH /api/admin/phishing-automation/[companyId]
 *   Upsert a company's three automation gate flags.
 *   Body: { autoParse: boolean, autoClassify: boolean, autoReport: boolean }
 *   Client always sends all three current values (the admin page knows them
 *   from local state), avoiding partial-update SQL complexity.
 *
 * DELETE /api/admin/phishing-automation/[companyId]
 *   Remove the explicit override — company reverts to the all-OFF default.
 */

import { NextRequest, NextResponse } from 'next/server';
import { requireAdmin } from '@/lib/auth-utils';
import postgresClient from '@/lib/services/postgres-client';

export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ companyId: string }> }
) {
  const { session, error } = await requireAdmin();
  if (error) return error;

  const { companyId } = await params;
  const id = parseInt(companyId, 10);
  if (isNaN(id)) return NextResponse.json({ error: 'Invalid companyId' }, { status: 400 });

  const body = await request.json().catch(() => null);
  if (
    body == null ||
    typeof body.autoParse !== 'boolean' ||
    typeof body.autoClassify !== 'boolean' ||
    typeof body.autoReport !== 'boolean'
  ) {
    return NextResponse.json(
      { error: 'body.autoParse, body.autoClassify, body.autoReport (all boolean) required' },
      { status: 400 }
    );
  }

  const userEmail = (session?.user as any)?.email ?? null;

  await postgresClient.query(
    `INSERT INTO phishing_automation_gate (company_id, auto_parse, auto_classify, auto_report, updated_by, updated_at)
          VALUES ($1, $2, $3, $4, $5, NOW())
     ON CONFLICT (company_id)
     DO UPDATE SET auto_parse = EXCLUDED.auto_parse,
                   auto_classify = EXCLUDED.auto_classify,
                   auto_report = EXCLUDED.auto_report,
                   updated_by = EXCLUDED.updated_by,
                   updated_at = NOW()`,
    [id, body.autoParse, body.autoClassify, body.autoReport, userEmail]
  );

  return NextResponse.json({
    ok: true,
    companyId: id,
    autoParse: body.autoParse,
    autoClassify: body.autoClassify,
    autoReport: body.autoReport,
  });
}

export async function DELETE(
  _request: NextRequest,
  { params }: { params: Promise<{ companyId: string }> }
) {
  const { error } = await requireAdmin();
  if (error) return error;

  const { companyId } = await params;
  const id = parseInt(companyId, 10);
  if (isNaN(id)) return NextResponse.json({ error: 'Invalid companyId' }, { status: 400 });

  await postgresClient.query(`DELETE FROM phishing_automation_gate WHERE company_id = $1`, [id]);
  return NextResponse.json({ ok: true });
}
