/**
 * GET  /api/analyzer/tickets/:ticketNumber/links
 *   Cheap explicit-only discovery (regex + RELATED TICKETS section + problem_ticket_id).
 *   No LLM cost. Use this on page load to render the Related Tickets panel.
 *
 * POST /api/analyzer/tickets/:ticketNumber/links
 *   Body: { includeSuggested?: boolean }
 *   Runs the Haiku-suggested arm in addition to the explicit arm.
 */

import { NextRequest, NextResponse } from 'next/server';
import { requireAuth } from '@/lib/auth-utils';
import {
  loadTicketBundle,
  TicketNotFoundError,
} from '@/lib/services/analyzer/data-access';
import {
  discoverLinks,
  discoverExplicitLinks,
} from '@/lib/services/analyzer/link-discovery';
import { SuggestLinksRequest } from '@/lib/types/analyzer';

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

  const { ticketNumber } = await params;

  let bundle;
  try {
    bundle = await loadTicketBundle(ticketNumber);
  } catch (err) {
    if (err instanceof TicketNotFoundError) {
      return NextResponse.json(
        { error: `Ticket ${ticketNumber} not found in local mirror` },
        { status: 404 }
      );
    }
    console.error('[analyzer/links] data-access error:', err);
    return NextResponse.json(
      { error: 'Failed to load ticket' },
      { status: 500 }
    );
  }

  const result = await discoverExplicitLinks(bundle);
  return NextResponse.json({
    explicit: result.explicit,
    suggested: [],
    isProblemTicket: result.isProblemTicket,
    problemTicketSignals: result.problemTicketSignals,
  });
}

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ ticketNumber: string }> }
) {
  const { error } = await requireAuth();
  if (error) return error;

  const { ticketNumber } = await params;

  const body = await request.json().catch(() => ({}));
  const parsed = SuggestLinksRequest.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json(
      { error: 'Invalid request body', details: parsed.error.issues },
      { status: 400 }
    );
  }

  let bundle;
  try {
    bundle = await loadTicketBundle(ticketNumber);
  } catch (err) {
    if (err instanceof TicketNotFoundError) {
      return NextResponse.json(
        { error: `Ticket ${ticketNumber} not found in local mirror` },
        { status: 404 }
      );
    }
    console.error('[analyzer/links] data-access error:', err);
    return NextResponse.json(
      { error: 'Failed to load ticket' },
      { status: 500 }
    );
  }

  const result = await discoverLinks(bundle, {
    includeSuggested: parsed.data.includeSuggested,
  });
  return NextResponse.json(result);
}
