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

export async function GET() {
  try {
    const [statuses, resources, companies, issueTypes, subIssueTypes, queues, configItems, priorities, ticketCategories] = await Promise.all([
      postgresClient.query(`SELECT value, label FROM statuses WHERE is_deleted = false ORDER BY value`),
      postgresClient.query(`SELECT id, first_name, last_name FROM resources WHERE is_deleted = false ORDER BY last_name, first_name`),
      postgresClient.query(`SELECT id, company_name FROM companies WHERE is_deleted = false ORDER BY company_name`),
      postgresClient.query(`SELECT value, label FROM issue_types WHERE is_deleted = false ORDER BY label`),
      postgresClient.query(`SELECT value, label, parent_value FROM sub_issue_types WHERE is_deleted = false ORDER BY label`),
      postgresClient.query(`SELECT value, label FROM queues WHERE is_active = true ORDER BY label`),
      postgresClient.query(`SELECT id, reference_title FROM configuration_items WHERE is_deleted = false AND reference_title IS NOT NULL ORDER BY reference_title`),
      postgresClient.query(`SELECT value, label FROM priorities WHERE is_active = true ORDER BY sort_order, value`),
      postgresClient.query(`SELECT value, label FROM ticket_categories WHERE is_active = true ORDER BY sort_order, value`),
    ]);

    return NextResponse.json({
      statuses: statuses.rows,
      resources: resources.rows.map((r: any) => ({
        id: r.id,
        name: [r.first_name, r.last_name].filter(Boolean).join(' ').trim() || `Resource ${r.id}`,
      })),
      companies: companies.rows.map((c: any) => ({ id: c.id, name: c.company_name })),
      issueTypes: issueTypes.rows,
      subIssueTypes: subIssueTypes.rows,
      queues: queues.rows,
      configItems: configItems.rows.map((r: any) => ({ id: r.id, name: r.reference_title })),
      priorities: priorities.rows,
      ticketCategories: ticketCategories.rows,
    });
  } catch (error) {
    console.error('Failed to fetch lookups:', error);
    return NextResponse.json({ error: 'Failed to fetch lookups' }, { status: 500 });
  }
}
