import { NextRequest, NextResponse } from 'next/server';
import { verifySession } from '@/lib/auth';
import { pgGetAttendanceRecords } 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 month = Number(url.searchParams.get('month') || new Date().getMonth() + 1);
    const year = Number(url.searchParams.get('year') || new Date().getFullYear());

    if (!Number.isInteger(month) || month < 1 || month > 12) {
      return NextResponse.json({ error: 'Invalid month' }, { status: 400 });
    }

    if (!Number.isInteger(year) || year < 2000 || year > 2100) {
      return NextResponse.json({ error: 'Invalid year' }, { status: 400 });
    }

    const fromDate = `${year}-${String(month).padStart(2, '0')}-01`;
    const toDate = new Date(year, month, 0).toISOString().slice(0, 10);

    const records = await pgGetAttendanceRecords({
      page: 1,
      pageSize: 1000,
      employeeId: session.user.id,
      fromDate,
      toDate,
    });

    const items = (records.items || []) as any[];

    const summary = items.reduce(
      (acc, item) => {
        const status = String(item.record_type || '');
        if (status === 'present') acc.presentDays += 1;
        if (status === 'absent') acc.absentDays += 1;
        if (status === 'late') acc.lateCount += 1;
        if (status === 'sick') acc.sickDays += 1;
        if (status === 'leave') acc.leaveDays += 1;
        acc.totalHours += Number(item.duration_hours || 0);
        return acc;
      },
      {
        presentDays: 0,
        absentDays: 0,
        lateCount: 0,
        sickDays: 0,
        leaveDays: 0,
        totalHours: 0,
      }
    );

    return NextResponse.json({
      month,
      year,
      fromDate,
      toDate,
      items,
      summary: {
        ...summary,
        totalHours: Math.round(summary.totalHours * 100) / 100,
      },
    });
  } catch (error) {
    console.error('Error fetching employee attendance history:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
