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,
  pgApproveAttendanceRecord,
  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 === 'approved') {
      return NextResponse.json({ error: 'Record already approved' }, { status: 400 });
    }

    const body = await request.json();
    const approvedRecord = await pgApproveAttendanceRecord(id, session.user.id, body.reason);

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