import { NextRequest, NextResponse } from 'next/server';
import { verifySession } from '@/lib/auth';
import {
  pgCreateAttendanceCorrectionRequest,
  pgGetAttendanceCorrectionRequests,
  pgGetAttendanceRecordById,
} from '@/lib/postgres/attendance';

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

    const url = new URL(request.url);
    const page = Math.max(1, Number(url.searchParams.get('page') || 1));
    const pageSize = Math.max(10, Math.min(200, Number(url.searchParams.get('pageSize') || 50)));
    const status = url.searchParams.get('status') || undefined;

    const result = await pgGetAttendanceCorrectionRequests({
      page,
      pageSize,
      employeeId: session.user.id,
      status,
    });

    return NextResponse.json(result);
  } catch (error) {
    console.error('Error fetching employee correction requests:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

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

    const body = await request.json();
    const {
      recordId,
      reason,
      requestedRecordType,
      requestedCheckInTime,
      requestedCheckOutTime,
    } = body as {
      recordId?: string;
      reason?: string;
      requestedRecordType?: string;
      requestedCheckInTime?: string;
      requestedCheckOutTime?: string;
    };

    if (!recordId || !reason?.trim()) {
      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
    }

    const record = await pgGetAttendanceRecordById(recordId);
    if (!record) {
      return NextResponse.json({ error: 'Attendance record not found' }, { status: 404 });
    }

    if (String(record.employee_id || '') !== session.user.id) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    const created = await pgCreateAttendanceCorrectionRequest({
      recordId,
      employeeId: session.user.id,
      reason: reason.trim(),
      requestedRecordType,
      requestedCheckInTime,
      requestedCheckOutTime,
    });

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