/**
 * GET /api/analyzer/tickets/filter-options
 *
 * Returns the dropdown source data for the analyzer ticket browser.
 * Companies are limited to those that have at least one non-deleted ticket
 * (255 → typically ~150 with tickets) so the dropdown isn't padded with
 * dormant accounts. Resources are limited to active ones with at least one
 * assigned ticket.
 */

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

interface CompanyRow { id: string; company_name: string }
interface IssueTypeRow { value: number; label: string }
interface QueueRow { value: number; label: string }
interface StatusRow { value: number; label: string }
interface PriorityRow { value: number; label: string }
interface ResourceRow { id: string; full_name: string }

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

  const [companies, issueTypes, queues, statuses, priorities, resources] =
    await Promise.all([
      postgresClient.query<CompanyRow>(
        `SELECT c.id::text AS id, c.company_name
           FROM companies c
          WHERE c.is_active = true
            AND c.is_deleted = false
            AND EXISTS (
              SELECT 1 FROM tickets t
               WHERE t.company_id = c.id AND t.is_deleted = false
            )
          ORDER BY c.company_name`
      ),
      postgresClient.query<IssueTypeRow>(
        `SELECT value, label FROM issue_types
          WHERE is_active = true AND is_deleted = false
          ORDER BY sort_order NULLS LAST, label`
      ),
      postgresClient.query<QueueRow>(
        `SELECT value, label FROM queues
          WHERE is_active = true AND is_deleted = false
          ORDER BY sort_order NULLS LAST, label`
      ),
      postgresClient.query<StatusRow>(
        `SELECT value, label FROM statuses
          WHERE is_active = true AND is_deleted = false
          ORDER BY sort_order NULLS LAST, label`
      ),
      postgresClient.query<PriorityRow>(
        // priorities has no is_deleted column (no soft-delete on this small table)
        `SELECT value, label FROM priorities
          WHERE is_active = true
          ORDER BY value`
      ),
      postgresClient.query<ResourceRow>(
        `SELECT r.id::text AS id,
                trim(coalesce(r.first_name,'') || ' ' || coalesce(r.last_name,'')) AS full_name
           FROM resources r
          WHERE r.is_active = true
            AND r.is_deleted = false
            AND EXISTS (
              SELECT 1 FROM tickets t
               WHERE t.assigned_resource_id = r.id AND t.is_deleted = false
            )
          ORDER BY 2`
      ),
    ]);

  return NextResponse.json({
    companies: companies.rows.map((r) => ({ id: r.id, name: r.company_name })),
    issueTypes: issueTypes.rows,
    queues: queues.rows,
    statuses: statuses.rows,
    priorities: priorities.rows,
    resources: resources.rows.map((r) => ({ id: r.id, name: r.full_name })),
  });
}
