import { NextRequest, NextResponse } from 'next/server';
import {
  pgGetBankReconciliationPeriodById,
  pgUpdateBankReconciliationPeriod,
} from '@/lib/postgres/bank-reconciliation';
import type { BankReconciliationPeriod } from '@/lib/types';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const period = await pgGetBankReconciliationPeriodById(id);

    if (!period) {
      return NextResponse.json(
        { error: 'Reconciliation period not found' },
        { status: 404 }
      );
    }

    return NextResponse.json(period, { status: 200 });
  } catch (error) {
    console.error('Error fetching reconciliation period:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}

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

    const updated = await pgUpdateBankReconciliationPeriod(id, body);

    if (!updated) {
      return NextResponse.json(
        { error: 'Reconciliation period not found' },
        { status: 404 }
      );
    }

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