/**
 * GET /api/analyzer/itglue/applications/:id
 *
 * Returns the asset row + its type's field schema (with hints) so the
 * detail page can render fields in IT Glue's order with empty fields shown
 * muted. Read-only.
 */

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

interface AssetRow {
  id: string;
  name: string | null;
  organization_id: string | null;
  organization_name: string | null;
  flexible_asset_type_id: string;
  flexible_asset_type_name: string | null;
  traits: Record<string, unknown>;
  created_at: Date | null;
  updated_at: Date | null;
}

interface FieldRow {
  id: string;
  name: string;
  kind: string | null;
  hint: string | null;
  required: boolean;
}

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

  const { id } = await params;

  const assetRes = await postgresClient.query<AssetRow & { autotask_company_id: string | null }>(
    `SELECT a.id::text                       AS id,
            a.name,
            a.organization_id::text          AS organization_id,
            a.organization_name,
            a.flexible_asset_type_id::text   AS flexible_asset_type_id,
            a.flexible_asset_type_name,
            a.traits,
            a.created_at,
            a.updated_at,
            comp.id::text                    AS autotask_company_id
       FROM itg_flexible_assets a
       LEFT JOIN companies comp ON LOWER(comp.company_name) = LOWER(a.organization_name)
      WHERE a.id = $1
      LIMIT 1`,
    [id]
  );
  if (assetRes.rowCount === 0) {
    return NextResponse.json({ error: 'Asset not found' }, { status: 404 });
  }
  const a = assetRes.rows[0];

  const fieldsRes = await postgresClient.query<FieldRow>(
    `SELECT id::text AS id, name, kind, hint, required
       FROM itg_flexible_asset_fields
      WHERE flexible_asset_type_id = $1
      ORDER BY id`,
    [a.flexible_asset_type_id]
  );

  return NextResponse.json({
    asset: {
      id: a.id,
      name: a.name,
      organizationId: a.organization_id,
      organizationName: a.organization_name,
      flexibleAssetTypeId: a.flexible_asset_type_id,
      flexibleAssetTypeName: a.flexible_asset_type_name,
      autotaskCompanyId: a.autotask_company_id,
      traits: redact(a.traits ?? {}),
      createdAt: a.created_at?.toISOString() ?? null,
      updatedAt: a.updated_at?.toISOString() ?? null,
    },
    fields: fieldsRes.rows,
  });
}
