import { NextRequest, NextResponse } from 'next/server';
import {
  pgGetBankReconciliationPeriodById,
  pgDeleteReconciliationMatch,
} from '@/lib/postgres/bank-reconciliation';

/**
 * DELETE /api/admin/bank-reconciliation/periods/[id]/matches/[matchId]
 * Removes a reconciliation match and reverts ledger transaction statuses.
 */
export async function DELETE(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string; matchId: string }> }
) {
  try {
    const { id: periodId, matchId } = await params;

    const period = await pgGetBankReconciliationPeriodById(periodId);
    if (!period) {
      return NextResponse.json({ error: 'Period not found' }, { status: 404 });
    }

    if (period.status === 'locked') {
      return NextResponse.json({ error: 'الفترة مقفلة ولا يمكن تعديل مطابقاتها' }, { status: 409 });
    }

    const deleted = await pgDeleteReconciliationMatch(matchId);
    if (!deleted) {
      return NextResponse.json({ error: 'Match not found' }, { status: 404 });
    }

    return NextResponse.json({ success: true, matchId }, { status: 200 });
  } catch (error) {
    console.error('Error deleting match:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}
