/**
 * PATCH /api/admin/company-scope/[companyId]
 *   Upsert a company's in_scope flag.
 *   Body: { inScope: boolean }
 *
 * DELETE /api/admin/company-scope/[companyId]
 *   Remove the explicit override — company reverts to implicitly in scope.
 */

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.inScope !== 'boolean') {
    return NextResponse.json({ error: 'body.inScope (boolean) required' }, { status: 400 });
  }

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

  await postgresClient.query(
    `INSERT INTO company_scope (company_id, in_scope, updated_by, updated_at)
          VALUES ($1, $2, $3, NOW())
     ON CONFLICT (company_id)
     DO UPDATE SET in_scope = EXCLUDED.in_scope,
                   updated_by = EXCLUDED.updated_by,
                   updated_at = NOW()`,
    [id, body.inScope, userEmail]
  );

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

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 company_scope WHERE company_id = $1`, [id]);
  return NextResponse.json({ ok: true });
}
