import { NextResponse } from 'next/server';
import { getSession } from '@/lib/auth';
import { hasEmployeePermission } from '@/lib/employee-permissions';
import type { Employee, InternalTransferDocument, Warehouse } from '@/lib/types';

export async function GET() {
  const session = await getSession();
  const user = session?.user;

  if (!user) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const {
      pgGetSettings,
      pgGetWarehouses,
      pgGetInternalTransfers,
      pgGetEmployees,
    } = await import('@/lib/postgres/data-access');

    const settings = await pgGetSettings();
    const canAccessAdminWorkTasks = hasEmployeePermission(user, settings, 'admin.work-tasks');
    const canAccessEmployeeWorkTasks = hasEmployeePermission(user, settings, 'employee.work-tasks');
    const canAccessMyTasks = hasEmployeePermission(user, settings, 'employee.my-tasks');

    if (!canAccessAdminWorkTasks && !canAccessEmployeeWorkTasks && !canAccessMyTasks) {
      return NextResponse.json({ workTasksCount: 0, myTasksCount: 0, total: 0 });
    }

    const [warehousesResult, transfersResult, employeesResult] = await Promise.all([
      pgGetWarehouses({ page: 1, pageSize: 5000 }),
      pgGetInternalTransfers({ page: 1, pageSize: 5000 }),
      pgGetEmployees({ page: 1, pageSize: 5000 }),
    ]);

    const warehouses = (warehousesResult.items || []) as Warehouse[];
    const warehouseIds = canAccessAdminWorkTasks
      ? warehouses.map((warehouse) => warehouse.id)
      : (user.warehouseIds ?? []);
    const allowedIds = new Set(warehouseIds.filter(Boolean));

    const transfers = ((transfersResult.items || []) as InternalTransferDocument[]).map((doc) => ({
      ...doc,
      receiptStatus: doc.receiptStatus ?? 'pending',
    }));

    const incomingPending = transfers.filter((doc) => {
      if (doc.status !== 'active') return false;
      if ((doc.receiptStatus ?? 'pending') !== 'pending') return false;
      return doc.items.some((item) => allowedIds.has(item.toWarehouseId));
    }).length;

    const approvalsPending = transfers.filter((doc) => {
      if (doc.status !== 'active') return false;
      return doc.items.some((item) => item.overageStatus === 'pending' && allowedIds.has(item.fromWarehouseId));
    }).length;

    const employees = (employeesResult.items || []) as Employee[];
    const myTasksCount = canAccessMyTasks && user.id
      ? employees.reduce((count, employee) => {
          const requests = employee.leaveRequests || [];
          return count + requests.filter((request) => request.toEmployeeId === user.id && request.status === 'pending').length;
        }, 0)
      : 0;

    const workTasksCount = incomingPending + approvalsPending;
    const total = workTasksCount + myTasksCount;

    return NextResponse.json({
      workTasksCount,
      myTasksCount,
      total,
      updatedAt: Date.now(),
    });
  } catch {
    return NextResponse.json({ workTasksCount: 0, myTasksCount: 0, total: 0 });
  }
}