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

export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const body = await request.json();

    const {
      status,
      reconciliationPeriodId,
    } = body;

    if (!status) {
      return NextResponse.json(
        { error: 'status is required' },
        { status: 400 }
      );
    }

    const success = await pgUpdateLedgerTransactionReconciliationStatus(
      id,
      status,
      reconciliationPeriodId
    );

    if (!success) {
      return NextResponse.json(
        { error: 'Ledger transaction not found' },
        { status: 404 }
      );
    }

    return NextResponse.json(
      { message: 'Ledger transaction updated successfully' },
      { status: 200 }
    );
  } catch (error) {
    console.error('Error updating ledger transaction status:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}
