/**
 * GET /api/analyzer/itglue/configurations/:id
 *
 * Returns one Configuration row + the curated field schema (with hints) so
 * the detail page renders fields in a stable order.
 */

import { NextRequest, NextResponse } from 'next/server';
import { requireAuth } from '@/lib/auth-utils';
import postgresClient from '@/lib/services/postgres-client';
import { _ASSET_AUDIT_INTERNALS } from '@/lib/services/analyzer/asset-audit/data-builder';

interface ConfigRow {
  id: string;
  organization_id: string | null;
  organization_name: string | null;
  configuration_type_id: string | null;
  configuration_type_name: string | null;
  configuration_status_id: string | null;
  configuration_status_name: string | null;
  manufacturer_name: string | null;
  model_name: string | null;
  operating_system_name: string | null;
  contact_id: string | null;
  location_id: string | null;
  name: string;
  hostname: string | null;
  primary_ip: string | null;
  mac_address: string | null;
  serial_number: string | null;
  asset_tag: string | null;
  position: string | null;
  notes: string | null;
  operating_system_notes: string | null;
  created_at: Date | null;
  updated_at: Date | null;
}

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

  const { id } = await params;

  const res = await postgresClient.query<ConfigRow & { rmm_id: string | null; autotask_company_id: string | null }>(
    `SELECT c.id::text                          AS id,
            c.organization_id::text             AS organization_id,
            c.organization_name,
            c.configuration_type_id::text       AS configuration_type_id,
            c.configuration_type_name,
            c.configuration_status_id::text     AS configuration_status_id,
            c.configuration_status_name,
            c.manufacturer_name, c.model_name,
            c.operating_system_name,
            c.contact_id::text                  AS contact_id,
            c.location_id::text                 AS location_id,
            c.name, c.hostname, c.primary_ip, c.mac_address, c.serial_number, c.asset_tag,
            c.position, c.notes, c.operating_system_notes,
            c.created_at, c.updated_at,
            c.rmm_id,
            comp.id::text                       AS autotask_company_id
       FROM itg_configurations c
       LEFT JOIN companies comp ON LOWER(comp.company_name) = LOWER(c.organization_name)
      WHERE c.id = $1
      LIMIT 1`,
    [id]
  );
  if (res.rowCount === 0) {
    return NextResponse.json({ error: 'Configuration not found' }, { status: 404 });
  }
  const c = res.rows[0];

  // If we have an rmm_id, look up the Datto device uid for the picker.
  let dattoDeviceUid: string | null = null;
  if (c.rmm_id) {
    const drmm = await postgresClient.query<{ uid: string }>(
      `SELECT uid FROM datto_rmm_devices WHERE id::text = $1 OR uid = $1 LIMIT 1`,
      [c.rmm_id]
    );
    dattoDeviceUid = drmm.rows[0]?.uid ?? null;
  }
  // Fallback: hostname-based device lookup.
  if (!dattoDeviceUid && c.hostname) {
    const drmm = await postgresClient.query<{ uid: string }>(
      `SELECT uid FROM datto_rmm_devices WHERE LOWER(hostname) = LOWER($1) LIMIT 1`,
      [c.hostname]
    );
    dattoDeviceUid = drmm.rows[0]?.uid ?? null;
  }

  return NextResponse.json({
    asset: {
      id: c.id,
      name: c.name,
      hostname: c.hostname,
      organizationId: c.organization_id,
      organizationName: c.organization_name,
      typeId: c.configuration_type_id,
      typeName: c.configuration_type_name,
      statusName: c.configuration_status_name,
      manufacturerName: c.manufacturer_name,
      modelName: c.model_name,
      operatingSystemName: c.operating_system_name,
      contactId: c.contact_id,
      locationId: c.location_id,
      dattoDeviceUid,
      autotaskCompanyId: c.autotask_company_id,
      // Synthesized "fields" map keyed by the audit field names.
      traits: {
        name: c.name,
        hostname: c.hostname,
        primary_ip: c.primary_ip,
        mac_address: c.mac_address,
        serial_number: c.serial_number,
        asset_tag: c.asset_tag,
        position: c.position,
        configuration_type_name: c.configuration_type_name,
        configuration_status_name: c.configuration_status_name,
        manufacturer_name: c.manufacturer_name,
        model_name: c.model_name,
        operating_system_name: c.operating_system_name,
        operating_system_notes: c.operating_system_notes,
        notes: c.notes,
        contact_id: c.contact_id,
        location_id: c.location_id,
      },
      createdAt: c.created_at?.toISOString() ?? null,
      updatedAt: c.updated_at?.toISOString() ?? null,
    },
    fields: _ASSET_AUDIT_INTERNALS.CONFIGURATION_FIELDS,
  });
}
