/**
 * GET /api/analyzer/itglue/configurations
 *
 * Returns Configuration records joined to their latest audit. Powers the
 * /analyzer/itglue/configurations listing page.
 */

import { NextRequest, NextResponse } from 'next/server';
import { requireAuth } from '@/lib/auth-utils';
import postgresClient from '@/lib/services/postgres-client';

interface Row {
  id: string;
  name: string;
  hostname: string | null;
  configuration_type_name: string | null;
  configuration_status_name: string | null;
  organization_id: string | null;
  organization_name: string | null;
  latest_audit_id: string | null;
  latest_audit_at: Date | null;
  latest_audit_score: number | null;
  latest_audit_provider: 'anthropic' | 'openrouter' | null;
}

export async function GET(_request: NextRequest) {
  const { error } = await requireAuth();
  if (error) return error;

  const res = await postgresClient.query<Row>(
    `SELECT c.id::text                                       AS id,
            c.name,
            c.hostname,
            c.configuration_type_name,
            c.configuration_status_name,
            c.organization_id::text                          AS organization_id,
            c.organization_name,
            la.id::text                                      AS latest_audit_id,
            la.generated_at                                  AS latest_audit_at,
            la.overall_score::float8                         AS latest_audit_score,
            la.provider                                      AS latest_audit_provider
       FROM itg_configurations c
       LEFT JOIN LATERAL (
         SELECT id, generated_at, overall_score, provider
           FROM itglue_asset_audits
          WHERE asset_type = 'configuration'
            AND asset_id = c.id
            AND status = 'complete'
          ORDER BY generated_at DESC
          LIMIT 1
       ) la ON true
      ORDER BY
        la.overall_score ASC NULLS FIRST,
        c.organization_name,
        c.name`
  );

  const configurations = res.rows.map((r) => ({
    id: r.id,
    name: r.name,
    hostname: r.hostname,
    typeName: r.configuration_type_name,
    statusName: r.configuration_status_name,
    organizationId: r.organization_id,
    organizationName: r.organization_name,
    latestAudit: r.latest_audit_id
      ? {
          id: r.latest_audit_id,
          generatedAt: r.latest_audit_at?.toISOString() ?? null,
          overallScore: r.latest_audit_score,
          provider: r.latest_audit_provider,
        }
      : null,
  }));
  return NextResponse.json({ configurations });
}
