/**
 * GET  /api/analyzer/analyses/:id/itglue-suggestions
 *   Returns matched IT Glue assets (flexible_asset + configuration) for the
 *   analysis, plus any existing ticket-scoped audits keyed by (assetType, assetId).
 *
 * POST /api/analyzer/analyses/:id/itglue-suggestions
 *   Body: { assetType: 'flexible_asset' | 'configuration', assetId, provider? }
 *   Runs a ticket-scoped audit (evidence = just this analysis). Returns the
 *   audit row.
 */

import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { requireAuth } from '@/lib/auth-utils';
import { matchAssetsForAnalysis } from '@/lib/services/analyzer/asset-audit/asset-matcher';
import { runAssetAudit } from '@/lib/services/analyzer/asset-audit/runner';
import {
  getAssetAuditById,
  getLatestTicketScopedAudit,
} from '@/lib/services/analyzer/asset-audit/persistence';
import {
  evaluateCost,
  recordCostAuditDecision,
} from '@/lib/services/analyzer/cost-guard';
import { ProviderEnum } from '@/lib/types/analyzer';

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

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

  const { id } = await params;
  const matched = await matchAssetsForAnalysis(id);
  if (!matched) {
    return NextResponse.json(
      { error: 'Analysis not found or not yet complete' },
      { status: 404 }
    );
  }

  // For each match, look up an existing ticket-scoped audit if any.
  const flexWithAudits = await Promise.all(
    matched.flexibleAssets.map(async (m) => ({
      ...m,
      latestAudit: await getLatestTicketScopedAudit(id, 'flexible_asset', m.id),
    }))
  );
  const configWithAudits = await Promise.all(
    matched.configurations.map(async (m) => ({
      ...m,
      latestAudit: await getLatestTicketScopedAudit(id, 'configuration', m.id),
    }))
  );

  return NextResponse.json({
    ticketNumber: matched.ticketNumber,
    organizationId: matched.organizationId,
    organizationName: matched.organizationName,
    flexibleAssets: flexWithAudits,
    configurations: configWithAudits,
  });
}

const PostBody = z.object({
  assetType: z.enum(['flexible_asset', 'configuration']),
  assetId: z.union([z.string(), z.number()]),
  provider: ProviderEnum.optional().default('anthropic'),
});

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

  const { id: analysisId } = await params;
  const body = await request.json().catch(() => ({}));
  const parsed = PostBody.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json(
      { error: 'Invalid request body', details: parsed.error.issues },
      { status: 400 }
    );
  }
  const { assetType, assetId, provider } = parsed.data;
  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: {
      mode: 'ticket_scoped',
      analysisId,
      assetType,
      assetId,
      provider,
    },
  });
  if (evaluation.decision === 'blocked') {
    return NextResponse.json(
      {
        error: 'Daily cost limit reached',
        message: evaluation.decisionReason,
      },
      { status: 403 }
    );
  }

  const result = await runAssetAudit({
    assetType,
    assetId,
    generatedByUserId: userId,
    provider,
    ticketScopeAnalysisId: analysisId,
  });

  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 });
}
