import { prisma } from "../../config/prisma";
import { BadRequestError } from "../../common/errors/http-errors";
import * as managerDashboardRepo from "./manager.dashboard.repo";

async function getManagerContext(userId: string) {
  const manager = await prisma.employee.findUnique({
    where: { userId },
    select: { id: true, organizationId: true, departmentId: true, role: true },
  });
  if (!manager) throw new BadRequestError("Manager profile not found");
  if (manager.role !== "MANAGER" && manager.role !== "ADMIN") {
    throw new BadRequestError("Access denied");
  }
  return manager;
}

export async function getTaskStats(userId: string) {
  const manager = await getManagerContext(userId);
  return managerDashboardRepo.getTaskStatsForManager(
    manager.organizationId,
    manager.role === "ADMIN" ? undefined : manager.departmentId,
  );
}

export async function getDecisionTrend(userId: string, days?: number) {
  const manager = await getManagerContext(userId);
  return managerDashboardRepo.getDecisionTrendForManager(
    manager.organizationId,
    days,
    manager.role === "ADMIN" ? undefined : manager.departmentId,
  );
}

export async function getTeamPerformance(userId: string) {
  const manager = await getManagerContext(userId);
  return managerDashboardRepo.getTeamPerformanceForManager(
    manager.organizationId,
    manager.role === "ADMIN" ? undefined : manager.departmentId,
  );
}
