import { NextRequest, NextResponse } from 'next/server';
import {
  saveSetupStep,
  type SetupStepStatus
} from '@/features/setup/server/setup-state.service';
import { AuthError, requireSystemRole } from '@/lib/auth/session';

const allowedStatuses = new Set<SetupStepStatus>([
  'not_started',
  'running',
  'passed',
  'warning',
  'failed',
  'skipped',
  'stale'
]);

export async function POST(request: NextRequest) {
  try {
    await requireSystemRole('super_admin');
    const body = (await request.json()) as {
      setupRunId?: string;
      stepKey?: string;
      status?: SetupStepStatus;
      inputHash?: string | null;
      output?: Record<string, unknown> | null;
      errors?: unknown[] | null;
      warnings?: unknown[] | null;
    };

    if (!body.stepKey || !body.status || !allowedStatuses.has(body.status)) {
      return NextResponse.json({ message: 'Invalid setup step payload' }, { status: 400 });
    }

    return NextResponse.json(
      await saveSetupStep({
        setupRunId: body.setupRunId,
        stepKey: body.stepKey,
        status: body.status,
        inputHash: body.inputHash ?? null,
        output: body.output ?? null,
        errors: body.errors ?? null,
        warnings: body.warnings ?? null
      })
    );
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    return NextResponse.json({ message: 'Unable to save setup step' }, { status: 500 });
  }
}
