/**
 * HR Banking API
 * GET - Get employee bank accounts
 * POST - Add bank account
 */

import { NextRequest, NextResponse } from 'next/server';
import {
  getEmployeeBankAccounts,
  addBankAccount,
} from '@/lib/autonomy/hr-banking';

export const dynamic = 'force-dynamic';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const employeeId = searchParams.get('employeeId');

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

    const accounts = await getEmployeeBankAccounts(employeeId);

    return NextResponse.json({ accounts });
  } catch (error: any) {
    console.error('Error fetching bank accounts:', error);
    return NextResponse.json(
      { error: 'Failed to fetch bank accounts', details: error.message },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const {
      employeeId,
      accountName,
      bankName,
      accountNumber,
      routingNumber,
      accountType,
      isPrimary,
      addedById,
    } = body;

    if (!employeeId || !accountName || !bankName || !accountNumber || !routingNumber) {
      return NextResponse.json(
        { error: 'employeeId, accountName, bankName, accountNumber, and routingNumber are required' },
        { status: 400 }
      );
    }

    const accountId = await addBankAccount(
      employeeId,
      {
        accountName,
        bankName,
        accountNumber,
        routingNumber,
        accountType,
        isPrimary,
      },
      addedById
    );

    return NextResponse.json({ accountId, message: 'Bank account added' });
  } catch (error: any) {
    console.error('Error adding bank account:', error);
    return NextResponse.json(
      { error: 'Failed to add bank account', details: error.message },
      { status: 500 }
    );
  }
}
