import { NextRequest, NextResponse } from 'next/server';
import {
  applyAutoMatchFromPreviewForPeriod,
  applyAutoMatchPreviewForPeriod,
  dryRunApplyAutoMatchFromPreviewForPeriod,
  dryRunApplyAutoMatchPreviewForPeriod,
  type ApplyPreviewInputSuggestion,
} 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 matchedBy = body?.matchedBy;
    const suggestions = Array.isArray(body?.suggestions) ? body.suggestions : [];
    const applyFromPreview = Boolean(body?.applyFromPreview);
    const dryRun = Boolean(body?.dryRun);
    const threshold = Number(body?.threshold ?? 80);

    if (!matchedBy || typeof matchedBy !== 'string') {
      return NextResponse.json(
        { error: 'matchedBy is required' },
        { status: 400 }
      );
    }

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

    let result;
    if (applyFromPreview) {
      result = dryRun
        ? await dryRunApplyAutoMatchFromPreviewForPeriod(id, threshold)
        : await applyAutoMatchFromPreviewForPeriod(id, matchedBy, threshold);
    } else {
      if (suggestions.length === 0) {
        return NextResponse.json(
          { error: 'suggestions array is required when applyFromPreview is false' },
          { status: 400 }
        );
      }

      const malformed = suggestions.some(
        (s: any) =>
          !s ||
          typeof s.bankTransactionId !== 'string' ||
          typeof s.ledgerTransactionId !== 'string'
      );

      if (malformed) {
        return NextResponse.json(
          { error: 'Each suggestion must include bankTransactionId and ledgerTransactionId' },
          { status: 400 }
        );
      }

      result = dryRun
        ? await dryRunApplyAutoMatchPreviewForPeriod(
            id,
            suggestions as ApplyPreviewInputSuggestion[]
          )
        : await applyAutoMatchPreviewForPeriod(
            id,
            matchedBy,
            suggestions as ApplyPreviewInputSuggestion[]
          );
    }

    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 applying auto-match preview suggestions:', error);
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
