import { NextRequest, NextResponse } from 'next/server';
import {
  pgCreateReconciliationMatch,
  pgGetReconciliationMatchesForPeriod,
} from '@/lib/postgres/bank-reconciliation';
import type { ReconciliationMatch } from '@/lib/types';

export async function GET(request: NextRequest) {
  try {
    const periodId = request.nextUrl.searchParams.get('periodId');

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

    const matches = await pgGetReconciliationMatchesForPeriod(periodId);

    return NextResponse.json(
      { items: matches, total: matches.length },
      { status: 200 }
    );
  } catch (error) {
    console.error('Error fetching reconciliation matches:', 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 {
      reconciliationPeriodId,
      bankTransactionId,
      ledgerTransactionIds,
      matchType,
      matchConfidence,
      matchedBy,
      notes,
      status,
    } = body;

    if (!reconciliationPeriodId || !bankTransactionId || !matchedBy) {
      return NextResponse.json(
        { error: 'Missing required fields' },
        { status: 400 }
      );
    }

    const match = await pgCreateReconciliationMatch({
      reconciliationPeriodId,
      bankTransactionId,
      ledgerTransactionIds: ledgerTransactionIds || [],
      matchType: matchType || 'manual',
      matchConfidence: matchConfidence || 100,
      matchDate: new Date().toISOString(),
      matchedBy,
      notes,
      status: status || 'matched',
    } as Omit<ReconciliationMatch, 'id' | 'createdAt' | 'updatedAt'>);

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