/**
 * Single Payroll Run API
 * GET - Get payroll run details
 * PATCH - Update payroll run status (submit, approve, process)
 */

import { NextRequest, NextResponse } from 'next/server';
import {
  getPayrollRun,
  submitPayrollForApproval,
  approvePayroll,
  processPayroll,
} from '@/lib/autonomy/hr-banking';

export const dynamic = 'force-dynamic';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ runId: string }> }
) {
  try {
    const { runId } = await params;
    const run = await getPayrollRun(runId);

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

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

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

    switch (action) {
      case 'submit':
        await submitPayrollForApproval(runId, userId);
        return NextResponse.json({ message: 'Payroll submitted for approval' });

      case 'approve':
        if (!userId) {
          return NextResponse.json(
            { error: 'userId is required for approval' },
            { status: 400 }
          );
        }
        await approvePayroll(runId, userId);
        return NextResponse.json({ message: 'Payroll approved' });

      case 'process':
        const result = await processPayroll(runId, userId);
        return NextResponse.json({
          message: 'Payroll processed',
          ...result,
        });

      default:
        return NextResponse.json(
          { error: 'Invalid action. Use: submit, approve, process' },
          { status: 400 }
        );
    }
  } catch (error: any) {
    console.error('Error updating payroll run:', error);
    return NextResponse.json(
      { error: 'Failed to update payroll run', details: error.message },
      { status: 500 }
    );
  }
}
