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 {
  pgGetAttendanceRecordById,
  pgRejectAttendanceRecord,
} 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 record = await pgGetAttendanceRecordById(id);
    if (!record) {
      return NextResponse.json({ error: 'Record not found' }, { status: 404 });
    }

    if (record.status === 'rejected') {
      return NextResponse.json({ error: 'Record already rejected' }, { status: 400 });
    }

    const body = await request.json();
    const rejectedRecord = await pgRejectAttendanceRecord(id, session.user.id, body.reason);

    return NextResponse.json(rejectedRecord);
  } catch (error) {
    console.error('Error rejecting attendance record:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
