import { NextRequest, NextResponse } from 'next/server';
import { verifySession } from '@/lib/auth';
import { hasEmployeePermission } from '@/lib/employee-permissions';
import { pgGetSettings } from '@/lib/postgres/data-access';
import {
  pgApproveAttendanceCorrectionRequest,
  pgGetAttendanceCorrectionRequestById,
} from '@/lib/postgres/attendance';

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await verifySession();
    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const settings = await pgGetSettings();
    if (!hasEmployeePermission(session.user, settings, 'admin.hr-attendance')) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    const { id } = await params;
    const corr = await pgGetAttendanceCorrectionRequestById(id);
    if (!corr) {
      return NextResponse.json({ error: 'Correction request not found' }, { status: 404 });
    }

    const body = await request.json();
    const approved = await pgApproveAttendanceCorrectionRequest(id, session.user.id, body?.reviewReason);

    return NextResponse.json(approved);
  } catch (error) {
    console.error('Error approving correction request:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
