import { NextRequest, NextResponse } from 'next/server';
import { previewAutoMatchForPeriod } from '@/lib/services/bank-reconciliation-auto-match';

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const body = await request.json().catch(() => ({}));
    const threshold = Number(body?.threshold ?? 80);

    if (!Number.isFinite(threshold) || threshold < 0 || threshold > 100) {
      return NextResponse.json(
        { error: 'threshold must be between 0 and 100' },
        { status: 400 }
      );
    }

    const result = await previewAutoMatchForPeriod(id, threshold);
    return NextResponse.json(result, { status: 200 });
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Internal Server Error';
    if (message === 'Reconciliation period not found') {
      return NextResponse.json({ error: message }, { status: 404 });
    }

    console.error('Error previewing auto-match:', error);
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
