import { NextRequest, NextResponse } from 'next/server';
import { sql } from 'drizzle-orm';

import { withAuth } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { errorResponse } from '@/lib/errors';

/**
 * Resolves a pasted UUID or invoice number to the (type, href) of its
 * detail page. Used by the CommandSearch paste-detection shortcut so a
 * pasted ID jumps directly to the entity instead of running through the
 * full multi-bucket search.
 *
 * UNION-of-singletons across the high-signal entity tables. Each branch
 * is a primary-key lookup so the cost is dominated by network, not the
 * database. Returns `{ found: false }` when the id doesn't exist OR
 * when it exists but in a different port (port-scoped on purpose so a
 * super-admin paste from another port doesn't silently navigate
 * cross-tenant).
 */
export const GET = withAuth(async (req: NextRequest, ctx) => {
  try {
    const id = req.nextUrl.searchParams.get('id')?.trim() ?? '';
    if (!id || id.length > 100) {
      return NextResponse.json({ found: false });
    }

    // One UNION query covers every primary key the user might paste.
    // Each branch is a constant-time index lookup.
    const rows = await db.execute<{ type: string; entity_id: string }>(sql`
      SELECT 'client'::text AS type, id AS entity_id FROM clients
        WHERE id = ${id} AND port_id = ${ctx.portId} AND archived_at IS NULL
      UNION ALL
      SELECT 'residential-client', id FROM residential_clients
        WHERE id = ${id} AND port_id = ${ctx.portId} AND archived_at IS NULL
      UNION ALL
      SELECT 'yacht', id FROM yachts
        WHERE id = ${id} AND port_id = ${ctx.portId} AND archived_at IS NULL
      UNION ALL
      SELECT 'company', id FROM companies
        WHERE id = ${id} AND port_id = ${ctx.portId} AND archived_at IS NULL
      UNION ALL
      SELECT 'interest', id FROM interests
        WHERE id = ${id} AND port_id = ${ctx.portId} AND archived_at IS NULL
      UNION ALL
      SELECT 'residential-interest', id FROM residential_interests
        WHERE id = ${id} AND port_id = ${ctx.portId} AND archived_at IS NULL
      UNION ALL
      SELECT 'berth', id FROM berths
        WHERE id = ${id} AND port_id = ${ctx.portId}
      UNION ALL
      SELECT 'invoice', id FROM invoices
        WHERE (id = ${id} OR invoice_number = ${id}) AND port_id = ${ctx.portId}
      UNION ALL
      SELECT 'expense', id FROM expenses
        WHERE id = ${id} AND port_id = ${ctx.portId}
      UNION ALL
      SELECT 'document', id FROM documents
        WHERE id = ${id} AND port_id = ${ctx.portId}
      LIMIT 1
    `);

    const list = Array.from(rows);
    if (list.length === 0) {
      return NextResponse.json({ found: false });
    }
    const row = list[0]!;

    const hrefMap: Record<string, string> = {
      client: `/${ctx.portSlug}/clients/${row.entity_id}`,
      'residential-client': `/${ctx.portSlug}/residential/clients/${row.entity_id}`,
      yacht: `/${ctx.portSlug}/yachts/${row.entity_id}`,
      company: `/${ctx.portSlug}/companies/${row.entity_id}`,
      interest: `/${ctx.portSlug}/interests/${row.entity_id}`,
      'residential-interest': `/${ctx.portSlug}/residential/interests/${row.entity_id}`,
      berth: `/${ctx.portSlug}/berths/${row.entity_id}`,
      invoice: `/${ctx.portSlug}/invoices/${row.entity_id}`,
      expense: `/${ctx.portSlug}/expenses/${row.entity_id}`,
      document: `/${ctx.portSlug}/documents/${row.entity_id}`,
    };

    return NextResponse.json({
      found: true,
      type: row.type,
      id: row.entity_id,
      href: hrefMap[row.type] ?? null,
    });
  } catch (error) {
    return errorResponse(error);
  }
});
