/**
 * GET  /api/analyzer/itglue/configurations/:id/audit
 * POST /api/analyzer/itglue/configurations/:id/audit
 *
 * Mirrors the Applications endpoint but for Configurations.
 */

import { NextRequest, NextResponse } from 'next/server';
import { requireAuth } from '@/lib/auth-utils';
import { RunAssetAuditRequest } from '@/lib/types/analyzer';
import { runAssetAudit } from '@/lib/services/analyzer/asset-audit/runner';
import {
  getAssetAuditById,
  getLatestAssetAudit,
  listAssetAudits,
} from '@/lib/services/analyzer/asset-audit/persistence';
import {
  evaluateCost,
  recordCostAuditDecision,
} from '@/lib/services/analyzer/cost-guard';

const PER_AUDIT_COST_USD: Record<'anthropic' | 'openrouter', number> = {
  anthropic: 0.1,
  openrouter: 0.01,
};

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { error } = await requireAuth();
  if (error) return error;

  const { id } = await params;
  const url = new URL(request.url);
  const includeHistory = url.searchParams.get('history') === '1';

  const latest = await getLatestAssetAudit(id, 'configuration');
  if (!includeHistory) return NextResponse.json({ audit: latest });
  const history = await listAssetAudits(id, 'configuration', 20);
  return NextResponse.json({ audit: latest, history });
}

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

  const { id } = await params;
  const body = await request.json().catch(() => ({}));
  const parsed = RunAssetAuditRequest.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json(
      { error: 'Invalid request body', details: parsed.error.issues },
      { status: 400 }
    );
  }
  const provider = parsed.data.provider;
  const userId = (session?.user as { id: string } | undefined)?.id ?? null;

  const evaluation = await evaluateCost({
    userId,
    estimatedCost: PER_AUDIT_COST_USD[provider],
    confirmedCost: false,
  });
  await recordCostAuditDecision({
    userId,
    action: 'itglue_audit',
    evaluation,
    context: { assetId: id, assetType: 'configuration', provider },
  });
  if (evaluation.decision === 'blocked') {
    return NextResponse.json(
      {
        error: 'Daily cost limit reached',
        message: evaluation.decisionReason,
      },
      { status: 403 }
    );
  }

  const result = await runAssetAudit({
    assetType: 'configuration',
    assetId: id,
    generatedByUserId: userId,
    provider,
  });

  if (result.status === 'failed') {
    return NextResponse.json(
      {
        error: 'Audit failed',
        message: result.errorMessage,
        auditId: result.auditId,
      },
      { status: 500 }
    );
  }

  const audit = await getAssetAuditById(result.auditId);
  return NextResponse.json({ audit });
}
