import { NextRequest, NextResponse } from 'next/server';
import {
  assertBootstrapSetupAvailable,
  assertBootstrapToken,
  BOOTSTRAP_ACTOR_ID,
  BOOTSTRAP_REQUIRED_STEPS,
  BootstrapSetupError,
  getBootstrapSetupStatus
} from '@/features/setup/server/setup-bootstrap.service';
import { completeSetupRun, getCurrentSetupRun } from '@/features/setup/server/setup-state.service';

export async function POST(request: NextRequest) {
  try {
    await assertBootstrapSetupAvailable();

    const body = (await request.json().catch(() => ({}))) as { bootstrapToken?: string; report?: Record<string, unknown> };
    assertBootstrapToken(body.bootstrapToken ?? request.headers.get('x-bootstrap-setup-token') ?? '');

    const currentRun = await getCurrentSetupRun();
    const completedStepKeys = new Set(
      currentRun.steps
        .filter((step) => step.status === 'passed' || step.status === 'warning')
        .map((step) => step.stepKey)
    );
    const missingSteps = BOOTSTRAP_REQUIRED_STEPS.filter(
      (step) => !completedStepKeys.has(step.stepKey)
    ).map((step) => step.stepKey);

    if (missingSteps.length > 0) {
      return NextResponse.json(
        {
          message: 'Complete all required bootstrap CSV steps before completing setup.',
          missingSteps
        },
        { status: 409 }
      );
    }

    const status = await getBootstrapSetupStatus();
    const missingChecks = Object.entries(status.checks)
      .filter(([key, passed]) => key !== 'completedSetupRun' && !passed)
      .map(([key]) => key);

    if (missingChecks.length > 0) {
      return NextResponse.json(
        {
          message: 'Bootstrap setup cannot complete until required setup data exists.',
          missingChecks
        },
        { status: 409 }
      );
    }

    const result = await completeSetupRun({
      actorId: BOOTSTRAP_ACTOR_ID,
      report: Object.assign(
        {
          source: 'bootstrap',
          checks: status.checks
        },
        body.report
      )
    });

    return NextResponse.json(result);
  } catch (error) {
    if (error instanceof BootstrapSetupError) {
      return NextResponse.json({ message: error.message, details: error.details }, { status: error.status });
    }

    return NextResponse.json({ message: 'Unable complete bootstrap setup' }, { status: 500 });
  }
}
