import { Role } from '@prisma/client';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { effectivePermissions } from '../../lib/permissions';

/**
 * Plant departments (Sprint 1, TEPL). An employee belongs to one; its
 * approvers decide the plant step of that employee's leave.
 */

const include = {
  approvers: { include: { user: { select: { id: true, name: true, email: true } } } },
  _count: { select: { employees: true } },
} as const;

const present = (d: { id: string; name: string; code: string | null; isArchived: boolean; approvers: { user: { id: string; name: string; email: string } }[]; _count: { employees: number } }) => ({
  id: d.id,
  name: d.name,
  code: d.code,
  isArchived: d.isArchived,
  employees: d._count.employees,
  approvers: d.approvers.map((a) => a.user),
});

export async function listDepartments(includeArchived = false) {
  const rows = await db.department.findMany({ where: includeArchived ? {} : { isArchived: false }, include, orderBy: [{ isArchived: 'asc' }, { name: 'asc' }] });
  return rows.map(present);
}

export async function createDepartment(input: { name: string; code?: string | null }) {
  const clash = await db.department.findFirst({ where: { name: { equals: input.name, mode: 'insensitive' } } });
  if (clash) throw new ConflictError('A department with that name already exists');
  const d = await db.department.create({ data: { tenantId: getTenantIdOrThrow(), name: input.name, code: input.code ?? null }, include });
  return present(d);
}

/** Find by name, or make it — the import names departments rather than choosing them. */
export async function departmentByName(name: string) {
  const found = await db.department.findFirst({ where: { name: { equals: name.trim(), mode: 'insensitive' } } });
  if (found) {
    if (found.isArchived) await db.department.update({ where: { id: found.id }, data: { isArchived: false } });
    return found.id;
  }
  return (await db.department.create({ data: { tenantId: getTenantIdOrThrow(), name: name.trim() } })).id;
}

export async function updateDepartment(id: string, input: { name?: string; code?: string | null; isArchived?: boolean }) {
  const d = await db.department.findFirst({ where: { id } });
  if (!d) throw new NotFoundError('Department not found');
  if (input.name && input.name.toLowerCase() !== d.name.toLowerCase()) {
    const clash = await db.department.findFirst({ where: { name: { equals: input.name, mode: 'insensitive' }, id: { not: id } } });
    if (clash) throw new ConflictError('A department with that name already exists');
  }
  await db.department.update({ where: { id }, data: input });
  return present(await db.department.findFirstOrThrow({ where: { id }, include }));
}

/** Staff who can be a department's plant approver: anyone holding APPROVE_PLANT_LEAVE. */
export async function plantApproverCandidates() {
  const users = await db.user.findMany({
    where: { role: { in: [Role.HOSTEL_ADMIN, Role.WARDEN, Role.MESS_ADMIN] }, deactivatedAt: null, hasLogin: true },
    select: { id: true, name: true, email: true, role: true, customRole: { select: { name: true, permissions: true } } },
    orderBy: { name: 'asc' },
    take: 500,
  });
  return users
    .filter((u) => u.role !== Role.HOSTEL_ADMIN && effectivePermissions(u.role, u.customRole?.permissions).includes('APPROVE_PLANT_LEAVE'))
    .map((u) => ({ id: u.id, name: u.name, email: u.email, roleName: u.customRole?.name ?? null }));
}

/** Replace a department's approvers. Each must hold APPROVE_PLANT_LEAVE. */
export async function setApprovers(id: string, userIds: string[]) {
  const d = await db.department.findFirst({ where: { id } });
  if (!d) throw new NotFoundError('Department not found');
  const allowed = new Set((await plantApproverCandidates()).map((u) => u.id));
  const bad = userIds.filter((u) => !allowed.has(u));
  if (bad.length) throw new BadRequestError('Each approver needs a role with “Approve plant leave”');
  const tenantId = getTenantIdOrThrow();
  await db.$transaction([
    db.departmentApprover.deleteMany({ where: { departmentId: id, userId: { notIn: userIds } } }),
    ...userIds.map((userId) =>
      db.departmentApprover.upsert({ where: { departmentId_userId: { departmentId: id, userId } }, create: { tenantId, departmentId: id, userId }, update: {} }),
    ),
  ]);
  return present(await db.department.findFirstOrThrow({ where: { id }, include }));
}

/** The departments this person approves for. */
export async function departmentsApprovedBy(userId: string) {
  return (await db.departmentApprover.findMany({ where: { userId }, select: { departmentId: true } })).map((r) => r.departmentId);
}
