/**
 * Ticket Reconciliation API Endpoint
 * POST /api/sync/reconcile-tickets - Trigger a stale-ticket reconciliation pass.
 * Public per middleware.ts (matches /api/sync/incremental). Fire-and-forget.
 */

import { NextRequest, NextResponse } from 'next/server';
import { reconcileStaleTickets } from '@/lib/services/ticket-reconciliation-service';

export async function POST(request: NextRequest) {
  try {
    const body = await request.json().catch(() => ({}));
    const triggeredBy = body.triggeredBy || 'api';

    // Non-blocking — same pattern as /api/sync/incremental.
    reconcileStaleTickets().catch((error) => {
      console.error('[RECONCILE] Ticket reconciliation failed:', error);
    });

    return NextResponse.json({
      message: 'Ticket reconciliation started',
      triggeredBy,
    });
  } catch (error) {
    console.error('Failed to start ticket reconciliation:', error);
    return NextResponse.json(
      { error: 'Failed to start ticket reconciliation' },
      { status: 500 }
    );
  }
}
