/**
 * GET /api/analyzer/itglue/applications
 *
 * Returns all Application flexible-asset records, joined to their latest
 * audit (if any). Powers /analyzer/itglue/applications listing page.
 */

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

const APPLICATION_TYPE_ID = 3790;

interface Row {
  id: string;
  name: string | null;
  organization_id: string | null;
  organization_name: string | null;
  trait_count: number;
  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 a.id::text                                       AS id,
            a.name,
            a.organization_id::text                          AS organization_id,
            a.organization_name,
            (SELECT COUNT(*)::int
               FROM jsonb_object_keys(a.traits) k)           AS trait_count,
            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_flexible_assets a
       LEFT JOIN LATERAL (
         SELECT id, generated_at, overall_score, provider
           FROM itglue_asset_audits
          WHERE asset_type = 'flexible_asset'
            AND asset_id = a.id
            AND status = 'complete'
          ORDER BY generated_at DESC
          LIMIT 1
       ) la ON true
      WHERE a.flexible_asset_type_id = $1
        AND COALESCE(a.archived, false) = false
      ORDER BY
        la.overall_score ASC NULLS FIRST,
        a.organization_name,
        a.name`,
    [APPLICATION_TYPE_ID]
  );

  const applications = res.rows.map((r) => ({
    id: r.id,
    name: r.name,
    organizationId: r.organization_id,
    organizationName: r.organization_name,
    traitCount: r.trait_count,
    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({ applications });
}
