import { NextRequest, NextResponse } from 'next/server'
import { TOMRulesEngine } from '@/lib/sdk/tom-generator/rules-engine'
import { TOMGeneratorState } from '@/lib/sdk/tom-generator/types'

/**
 * TOM Generator Controls Evaluation API
 *
 * POST /api/sdk/v1/tom-generator/controls/evaluate - Evaluate controls for given state
 *
 * Request body:
 * {
 *   state: TOMGeneratorState
 * }
 *
 * Response:
 * {
 *   evaluations: RulesEngineResult[]
 *   derivedTOMs: DerivedTOM[]
 *   summary: {
 *     total: number
 *     required: number
 *     recommended: number
 *     optional: number
 *     notApplicable: number
 *   }
 * }
 */

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { state } = body

    if (!state) {
      return NextResponse.json(
        { success: false, error: 'state is required in request body' },
        { status: 400 }
      )
    }

    // Parse dates in state
    const parsedState: TOMGeneratorState = {
      ...state,
      createdAt: new Date(state.createdAt),
      updatedAt: new Date(state.updatedAt),
      steps: state.steps?.map((step: { id: string; completed: boolean; data: unknown; validatedAt: string | null }) => ({
        ...step,
        validatedAt: step.validatedAt ? new Date(step.validatedAt) : null,
      })) || [],
      documents: [],
      derivedTOMs: [],
      gapAnalysis: null,
      exports: [],
    }

    // Initialize rules engine and evaluate
    const engine = new TOMRulesEngine()
    const evaluations = engine.evaluateControls(parsedState)
    const derivedTOMs = engine.deriveAllTOMs(parsedState)

    // Calculate summary
    const summary = {
      total: evaluations.length,
      required: evaluations.filter((e) => e.applicability === 'REQUIRED').length,
      recommended: evaluations.filter((e) => e.applicability === 'RECOMMENDED').length,
      optional: evaluations.filter((e) => e.applicability === 'OPTIONAL').length,
      notApplicable: evaluations.filter((e) => e.applicability === 'NOT_APPLICABLE').length,
    }

    // Group by category
    const byCategory: Record<string, typeof evaluations> = {}
    evaluations.forEach((e) => {
      const category = e.controlId.split('-')[1] // Extract category from ID like TOM-AC-01
      if (!byCategory[category]) {
        byCategory[category] = []
      }
      byCategory[category].push(e)
    })

    return NextResponse.json({
      success: true,
      data: {
        evaluations,
        derivedTOMs,
        summary,
        byCategory,
      },
    })
  } catch (error) {
    console.error('Failed to evaluate controls:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to evaluate controls' },
      { status: 500 }
    )
  }
}

export async function OPTIONS() {
  return NextResponse.json(
    { status: 'ok' },
    {
      headers: {
        Allow: 'POST, OPTIONS',
      },
    }
  )
}
