/**
 * HR Payroll API
 * GET - List payroll runs
 * POST - Create new payroll run
 */

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

export const dynamic = 'force-dynamic';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const status = searchParams.get('status') || undefined;
    const limit = parseInt(searchParams.get('limit') || '20');
    const offset = parseInt(searchParams.get('offset') || '0');

    const result = await getPayrollRuns({ status, limit, offset });

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

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { periodStart, periodEnd, createdById } = body;

    if (!periodStart || !periodEnd) {
      return NextResponse.json(
        { error: 'periodStart and periodEnd are required' },
        { status: 400 }
      );
    }

    const runId = await createPayrollRun(
      new Date(periodStart),
      new Date(periodEnd),
      createdById
    );

    return NextResponse.json({ runId, message: 'Payroll run created' });
  } catch (error: any) {
    console.error('Error creating payroll run:', error);
    return NextResponse.json(
      { error: 'Failed to create payroll run', details: error.message },
      { status: 500 }
    );
  }
}
