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

export async function GET(request: NextRequest) {
  try {
    const bankAccountId = request.nextUrl.searchParams.get('bankAccountId');
    const page = Number(request.nextUrl.searchParams.get('page') || 1);
    const pageSize = Number(request.nextUrl.searchParams.get('pageSize') || 50);

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

    const result = await pgListBankReconciliationPeriods(bankAccountId, { page, pageSize });

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

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();

    const {
      bankAccountId,
      periodStartDate,
      periodEndDate,
      statementStartBalance,
      statementEndBalance,
      createdBy,
    } = body;

    if (!bankAccountId || !periodStartDate || !periodEndDate || !statementEndBalance || !createdBy) {
      return NextResponse.json(
        { error: 'Missing required fields' },
        { status: 400 }
      );
    }

    const period = await pgCreateBankReconciliationPeriod({
      bankAccountId,
      periodStartDate,
      periodEndDate,
      statementStartBalance,
      statementEndBalance,
      status: 'draft',
      createdBy,
    } as Omit<BankReconciliationPeriod, 'id' | 'createdAt' | 'updatedAt'>);

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