import { NextResponse } from 'next/server';
import { requireAuth } from '@/lib/auth-helper';
import prisma from '@/lib/prisma';

// PUT - Update leave request status (Approve/Reject)
export async function PUT(
  request: Request,
  context: { params: Promise<{ id: string }> }
) {
  const auth = await requireAuth(['admin', 'hr']);
  if (auth.error) {
    return NextResponse.json({ error: auth.error }, { status: auth.status });
  }

  try {
    const body = await request.json();
    const { status, hodRemarks } = body;

    const { id } = await context.params;
    const leaveRequest = await prisma.leaveRequest.update({
      where: { id },
      data: {
        status,
        reviewComment: hodRemarks || undefined,
        hodApprovedBy: auth.user?.name || undefined,
        hodApprovedOn: status === 'Approved' ? new Date() : undefined,
        approvedOn: status === 'Approved' ? new Date() : undefined
      }
    });

    return NextResponse.json(leaveRequest);
  } catch (error) {
    console.error('Error updating leave request:', error);
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
  }
}

// DELETE - Cancel leave request
export async function DELETE(
  request: Request,
  context: { params: Promise<{ id: string }> }
) {
  const auth = await requireAuth();
  if (auth.error) {
    return NextResponse.json({ error: auth.error }, { status: auth.status });
  }

  try {
    const { id } = await context.params;
    await prisma.leaveRequest.delete({
      where: { id }
    });

    return NextResponse.json({ message: 'Leave request deleted successfully' });
  } catch (error) {
    console.error('Error deleting leave request:', error);
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
  }
}