﻿import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';

export async function GET(request: Request) {
  try {
    // Get the Authorization header
    const authHeader = request.headers.get('authorization');
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json({ error: 'Unauthorized - No token' }, { status: 401 });
    }
    
    const storedUserJson = authHeader.substring(7);
    let user;
    
    try {
      user = JSON.parse(storedUserJson);
    } catch (parseError) {
      return NextResponse.json({ error: 'Unauthorized - Invalid token' }, { status: 401 });
    }
    
    // Check role
    if (user.role !== 'admin' && user.role !== 'hr') {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }
    
    // Verify user still exists in database
    const dbUser = await prisma.user.findUnique({
      where: { id: user.id, isActive: true }
    });
    
    if (!dbUser) {
      return NextResponse.json({ error: 'Unauthorized - User not found' }, { status: 401 });
    }
    
    // Fetch stats
    const [
      totalEmployees,
      activeInterns,
      pendingLeave,
      upcomingTraining,
      openDisciplinary,
      payrollDue
    ] = await Promise.all([
      prisma.employee.count({ where: { isActive: true } }),
      prisma.employee.count({ where: { isActive: true, isIntern: true } }),
      prisma.leaveRequest.count({ where: { status: 'Pending' } }),
      prisma.trainingProgram.count({ where: { status: 'Upcoming' } }),
      prisma.disciplinaryCase.count({ where: { status: 'Open' } }),
      prisma.payrollRecord.count({ where: { status: 'Pending' } }),
    ]);
    
    return NextResponse.json({
      totalEmployees,
      activeInterns,
      pendingLeave,
      upcomingTraining,
      pendingAppraisals: 7,
      openDisciplinary,
      activeRecruitments: 3,
      payrollDue,
    });
  } catch (error) {
    console.error('Error fetching HR stats:', error);
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
  }
}
