import { Meal, Prisma, Role, StudentRequestStatus, StudentRequestType } from '@prisma/client';
import { paginated, type Pagination } from '../../lib/pagination';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { BadRequestError, ConflictError, ForbiddenError, NotFoundError } from '../../lib/errors';
import type { Permission } from '../../lib/permissions';
import { tenantHasFeature } from '../../middleware/requireFeature';
import { createRequest } from '../requests/requests.service';
import { issuePass } from '../gate/gate.service';
import { departmentsApprovedBy } from '../departments/departments.service';
import { inBackground, notifyLeavePlantPending, notifyRequestUpdated } from '../notifications/notifications.service';

/**
 * Leave under a policy (Sprint 1, TEPL). An employee applies for a type of
 * leave against a yearly balance; the hostel approves first, then a plant
 * approver for the employee's department. The final approval issues the
 * gate pass and switches the employee's meals off for those days.
 *
 * A leave is still a LEAVE request underneath, so the queue, the thread, the
 * gate and today's mobile app all keep working; a request without a leave
 * type (an older app) keeps the old one-step approval.
 *
 * Balances run January to December. A year's allocation is made the first
 * time it is needed: the type's yearly days plus what carries over from the
 * year before, up to the type's limit. Days used are counted from the
 * requests, never stored.
 */

const OPEN: StudentRequestStatus[] = [StudentRequestStatus.OPEN, StudentRequestStatus.IN_PROGRESS];
const DAY_MS = 86_400_000;
const IST_MS = 330 * 60_000;

/** Our default policy until TEPL sends theirs (docs/enterprise/defaults.md). */
const DEFAULT_TYPES = [
  { code: 'CL', name: 'Casual leave', yearlyDays: 12, carryForwardMax: 0, maxPerRequest: 3, noticeDays: 0, halfDayAllowed: true, needsPlantApproval: true, certificateAfterDays: null },
  { code: 'SL', name: 'Sick leave', yearlyDays: 12, carryForwardMax: 30, maxPerRequest: null, noticeDays: 0, halfDayAllowed: true, needsPlantApproval: true, certificateAfterDays: 3 },
  { code: 'EL', name: 'Earned leave', yearlyDays: 18, carryForwardMax: 45, maxPerRequest: null, noticeDays: 7, halfDayAllowed: false, needsPlantApproval: true, certificateAfterDays: null },
  { code: 'CO', name: 'Compensatory off', yearlyDays: 0, carryForwardMax: 0, maxPerRequest: 2, noticeDays: 0, halfDayAllowed: false, needsPlantApproval: true, certificateAfterDays: null },
  { code: 'HV', name: 'Home visit', yearlyDays: null, carryForwardMax: 0, maxPerRequest: null, noticeDays: 0, halfDayAllowed: false, needsPlantApproval: false, certificateAfterDays: null },
];

// ── Types ───────────────────────────────────────────────────────────────────

export async function listTypes(includeInactive = false) {
  if ((await db.leaveType.count()) === 0) {
    const tenantId = getTenantIdOrThrow();
    await db.leaveType.createMany({ data: DEFAULT_TYPES.map((t, i) => ({ ...t, tenantId, sortOrder: i })), skipDuplicates: true });
  }
  return db.leaveType.findMany({ where: includeInactive ? {} : { isActive: true }, orderBy: [{ isActive: 'desc' }, { sortOrder: 'asc' }] });
}

export interface LeaveTypeInput {
  code: string;
  name: string;
  yearlyDays: number | null;
  carryForwardMax: number;
  maxPerRequest: number | null;
  noticeDays: number;
  halfDayAllowed: boolean;
  needsPlantApproval: boolean;
  certificateAfterDays: number | null;
  isActive: boolean;
}

/** Save the whole policy. A type left out is switched off, not deleted: past leave keeps its name. */
export async function saveTypes(items: LeaveTypeInput[]) {
  const tenantId = getTenantIdOrThrow();
  const codes = items.map((t) => t.code.toUpperCase());
  if (new Set(codes).size !== codes.length) throw new BadRequestError('Two leave types share a code');
  await listTypes();
  await db.$transaction([
    db.leaveType.updateMany({ where: { code: { notIn: codes } }, data: { isActive: false } }),
    ...items.map((t, i) =>
      db.leaveType.upsert({
        where: { tenantId_code: { tenantId, code: t.code.toUpperCase() } },
        create: { ...t, code: t.code.toUpperCase(), tenantId, sortOrder: i },
        update: { ...t, code: t.code.toUpperCase(), sortOrder: i },
      }),
    ),
  ]);
  return listTypes(true);
}

// ── Balances ────────────────────────────────────────────────────────────────

const yearRange = (year: number) => ({ gte: new Date(Date.UTC(year, 0, 1)), lt: new Date(Date.UTC(year + 1, 0, 1)) });

/** Days approved and days still waiting, for one employee, type and year. */
async function usage(profileId: string, leaveTypeId: string, year: number) {
  const rows = await db.studentRequest.groupBy({
    by: ['status'],
    where: { studentProfileId: profileId, leaveTypeId, type: StudentRequestType.LEAVE, fromDate: yearRange(year), status: { in: [...OPEN, StudentRequestStatus.APPROVED] } },
    _sum: { leaveDays: true },
  });
  const sum = (s: StudentRequestStatus[]) => rows.filter((r) => s.includes(r.status)).reduce((n, r) => n + (r._sum.leaveDays ?? 0), 0);
  return { used: sum([StudentRequestStatus.APPROVED]), pending: sum(OPEN) };
}

/** The year's allocation, made on first need with the carry-over from the year before. */
async function allocation(profileId: string, type: { id: string; yearlyDays: number | null; carryForwardMax: number }, year: number) {
  const found = await db.leaveAllocation.findUnique({ where: { studentProfileId_leaveTypeId_year: { studentProfileId: profileId, leaveTypeId: type.id, year } } });
  if (found) return found;
  let carried = 0;
  if (type.carryForwardMax > 0) {
    const prev = await db.leaveAllocation.findUnique({ where: { studentProfileId_leaveTypeId_year: { studentProfileId: profileId, leaveTypeId: type.id, year: year - 1 } } });
    if (prev) {
      const u = await usage(profileId, type.id, year - 1);
      carried = Math.max(0, Math.min(type.carryForwardMax, prev.allotted + prev.carried + prev.adjustment - u.used));
    }
  }
  try {
    return await db.leaveAllocation.create({ data: { tenantId: getTenantIdOrThrow(), studentProfileId: profileId, leaveTypeId: type.id, year, allotted: type.yearlyDays ?? 0, carried } });
  } catch (e) {
    // Two requests made it at once: read the one that won.
    if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') {
      return db.leaveAllocation.findUniqueOrThrow({ where: { studentProfileId_leaveTypeId_year: { studentProfileId: profileId, leaveTypeId: type.id, year } } });
    }
    throw e;
  }
}

export async function balances(profileId: string, year: number) {
  const types = await listTypes();
  return Promise.all(
    types.map(async (t) => {
      const u = await usage(profileId, t.id, year);
      if (t.yearlyDays === null) return { type: t, year, tracked: false as const, used: u.used, pending: u.pending, allotted: null, carried: null, adjustment: null, available: null };
      const a = await allocation(profileId, t, year);
      return { type: t, year, tracked: true as const, used: u.used, pending: u.pending, allotted: a.allotted, carried: a.carried, adjustment: a.adjustment, available: a.allotted + a.carried + a.adjustment - u.used - u.pending };
    }),
  );
}

const balanceKey = (profileId: string, leaveTypeId: string, year: number) => `${profileId}|${leaveTypeId}|${year}`;

/**
 * The balance of one leave type in one year, for many people at once (Sprint
 * L4): the same numbers `balances(...)` gives for that type, from one usage
 * query a year and one allocation query. A missing allocation is made as
 * `balances` makes it, carry-over and all. A type switched off has no balance.
 */
async function balancesFor(keys: { profileId: string; leaveTypeId: string; year: number }[]) {
  const out = new Map<string, { available: number | null; used: number; pending: number }>();
  if (keys.length === 0) return out;
  const typeOf = new Map((await listTypes()).map((t) => [t.id, t]));
  const wanted = [...new Map(keys.filter((k) => typeOf.has(k.leaveTypeId)).map((k) => [balanceKey(k.profileId, k.leaveTypeId, k.year), k])).values()];
  if (wanted.length === 0) return out;
  const years = [...new Set(wanted.map((k) => k.year))];
  const used = new Map<string, { used: number; pending: number }>();
  await Promise.all(
    years.map(async (year) => {
      const these = wanted.filter((k) => k.year === year);
      const rows = await db.studentRequest.groupBy({
        by: ['studentProfileId', 'leaveTypeId', 'status'],
        where: { studentProfileId: { in: [...new Set(these.map((k) => k.profileId))] }, leaveTypeId: { in: [...new Set(these.map((k) => k.leaveTypeId))] }, type: StudentRequestType.LEAVE, fromDate: yearRange(year), status: { in: [...OPEN, StudentRequestStatus.APPROVED] } },
        _sum: { leaveDays: true },
      });
      for (const r of rows) {
        if (!r.leaveTypeId) continue;
        const key = balanceKey(r.studentProfileId, r.leaveTypeId, year);
        const u = used.get(key) ?? { used: 0, pending: 0 };
        if (r.status === StudentRequestStatus.APPROVED) u.used += r._sum.leaveDays ?? 0;
        else u.pending += r._sum.leaveDays ?? 0;
        used.set(key, u);
      }
    }),
  );
  const tracked = wanted.filter((k) => typeOf.get(k.leaveTypeId)!.yearlyDays !== null);
  const allocations = tracked.length
    ? await db.leaveAllocation.findMany({ where: { studentProfileId: { in: [...new Set(tracked.map((k) => k.profileId))] }, leaveTypeId: { in: [...new Set(tracked.map((k) => k.leaveTypeId))] }, year: { in: years } } })
    : [];
  const allocationOf = new Map(allocations.map((a) => [balanceKey(a.studentProfileId, a.leaveTypeId, a.year), a]));
  for (const k of wanted) {
    const key = balanceKey(k.profileId, k.leaveTypeId, k.year);
    const u = used.get(key) ?? { used: 0, pending: 0 };
    const type = typeOf.get(k.leaveTypeId)!;
    if (type.yearlyDays === null) {
      out.set(key, { available: null, used: u.used, pending: u.pending });
      continue;
    }
    // Made on first need, as `balances` does; rare once a year has started.
    const a = allocationOf.get(key) ?? (await allocation(k.profileId, type, k.year));
    out.set(key, { available: a.allotted + a.carried + a.adjustment - u.used - u.pending, used: u.used, pending: u.pending });
  }
  return out;
}

async function profileOf(userId: string) {
  const p = await db.studentProfile.findFirst({ where: { userId }, select: { id: true } });
  if (!p) throw new NotFoundError('No employee record for this account');
  return p.id;
}

export async function myBalances(userId: string, year: number) {
  return balances(await profileOf(userId), year);
}

/** Staff correcting a balance: comp-offs earned, a manual carry-over. */
export async function setAdjustment(profileId: string, leaveTypeId: string, year: number, adjustment: number, note: string | null) {
  const type = await db.leaveType.findFirst({ where: { id: leaveTypeId } });
  if (!type) throw new NotFoundError('Leave type not found');
  if (type.yearlyDays === null) throw new BadRequestError(`${type.name} has no balance to adjust`);
  if (!(await db.studentProfile.findFirst({ where: { id: profileId }, select: { id: true } }))) throw new NotFoundError('Employee not found');
  const a = await allocation(profileId, type, year);
  await db.leaveAllocation.update({ where: { id: a.id }, data: { adjustment, note } });
  return balances(profileId, year);
}

// ── Applying ────────────────────────────────────────────────────────────────

const day = (s: string) => new Date(`${s}T00:00:00.000Z`);
const todayIst = () => {
  const d = new Date(Date.now() + IST_MS);
  return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
};
const fmt = (n: number) => (Number.isInteger(n) ? String(n) : n.toFixed(1));

export async function applyLeave(userId: string, input: { leaveTypeId: string; fromDate: string; toDate: string; halfDay?: boolean; reason: string }) {
  const profileId = await profileOf(userId);
  const type = await db.leaveType.findFirst({ where: { id: input.leaveTypeId, isActive: true } });
  if (!type) throw new NotFoundError('Leave type not found');
  const from = day(input.fromDate);
  const to = day(input.toDate);
  if (to < from) throw new BadRequestError('Leave cannot end before it starts');
  if (from.getUTCFullYear() !== to.getUTCFullYear()) throw new BadRequestError('Apply separately for the days in each year');
  const halfDay = !!input.halfDay;
  if (halfDay && (!type.halfDayAllowed || from.getTime() !== to.getTime())) throw new BadRequestError(type.halfDayAllowed ? 'A half day is a single day' : `${type.name} cannot be taken as a half day`);
  const days = halfDay ? 0.5 : Math.round((to.getTime() - from.getTime()) / DAY_MS) + 1;
  if (type.maxPerRequest !== null && days > type.maxPerRequest) throw new BadRequestError(`${type.name} is up to ${fmt(type.maxPerRequest)} day${type.maxPerRequest === 1 ? '' : 's'} at a time`);
  const today = todayIst();
  if (from.getTime() < today.getTime() - 7 * DAY_MS) throw new BadRequestError('Leave can start at most a week back');
  if (type.noticeDays > 0 && from.getTime() < today.getTime() + type.noticeDays * DAY_MS) throw new BadRequestError(`${type.name} needs ${type.noticeDays} days' notice`);

  const clash = await db.studentRequest.findFirst({
    where: { studentProfileId: profileId, type: StudentRequestType.LEAVE, status: { in: [...OPEN, StudentRequestStatus.APPROVED] }, fromDate: { lte: to }, toDate: { gte: from } },
    select: { id: true },
  });
  if (clash) throw new ConflictError('You already have leave on some of those days');
  if (type.yearlyDays !== null) {
    const b = (await balances(profileId, from.getUTCFullYear())).find((x) => x.type.id === type.id);
    if (b && b.available !== null && b.available < days) throw new BadRequestError(`Only ${fmt(Math.max(0, b.available))} day${b.available === 1 ? '' : 's'} of ${type.name.toLowerCase()} left`);
  }

  const created = await createRequest(userId, {
    type: StudentRequestType.LEAVE,
    subject: `${type.name} · ${fmt(days)} day${days === 1 ? '' : 's'}`,
    body: input.reason,
    fromDate: input.fromDate,
    toDate: input.toDate,
  });
  await db.studentRequest.update({ where: { id: created.id }, data: { leaveTypeId: type.id, leaveDays: days, halfDay, leaveStage: 'HOSTEL' } });
  return getLeave(created.id);
}

// ── Approving ───────────────────────────────────────────────────────────────

const leaveInclude = {
  leaveType: { select: { id: true, code: true, name: true, needsPlantApproval: true } },
  student: {
    select: {
      id: true,
      employeeCode: true,
      departmentId: true,
      department: { select: { id: true, name: true } },
      user: { select: { id: true, name: true, phone: true } },
      bed: { select: { label: true, room: { select: { number: true } } } },
      property: { select: { id: true, name: true } },
    },
  },
} as const;

export function getLeave(id: string) {
  return db.studentRequest.findFirst({ where: { id }, include: leaveInclude });
}

export interface Approver {
  userId: string;
  role: Role;
  perms: Permission[];
}

/**
 * What waits on this person: the hostel step for those who run requests, the
 * plant step for their departments. With `pagination`, one page and the total
 * (Sprint L3), so each balance is worked out only for the rows on screen.
 */
export async function queue(viewer: Approver, stage: 'HOSTEL' | 'PLANT', propertyId?: string, pagination?: Pagination | null) {
  if (stage === 'HOSTEL' && !viewer.perms.includes('MANAGE_STUDENTS')) throw new ForbiddenError('Requires permission: MANAGE_STUDENTS');
  if (stage === 'PLANT' && !viewer.perms.includes('APPROVE_PLANT_LEAVE')) throw new ForbiddenError('Requires permission: APPROVE_PLANT_LEAVE');
  // The hostel step follows the block chosen in the top bar; a plant approver's departments span every block.
  const departmentFilter = stage === 'PLANT' && viewer.role !== Role.HOSTEL_ADMIN ? { student: { departmentId: { in: await departmentsApprovedBy(viewer.userId) } } } : stage === 'HOSTEL' && propertyId ? { student: { propertyId } } : {};
  const where: Prisma.StudentRequestWhereInput = { type: StudentRequestType.LEAVE, leaveTypeId: { not: null }, leaveStage: stage, status: { in: OPEN }, ...departmentFilter };
  const [rows, total] = await Promise.all([
    db.studentRequest.findMany({
      where,
      include: leaveInclude,
      orderBy: pagination ? [{ fromDate: 'asc' }, { id: 'asc' }] : { fromDate: 'asc' },
      ...(pagination ? { skip: pagination.skip, take: pagination.limit } : { take: 300 }),
    }),
    pagination ? db.studentRequest.count({ where }) : Promise.resolve(0),
  ]);
  // Every row's balance from a few grouped reads (Sprint L4), not a full balance sheet per row.
  const found = await balancesFor(rows.flatMap((r) => (r.leaveTypeId && r.fromDate ? [{ profileId: r.studentProfileId, leaveTypeId: r.leaveTypeId, year: r.fromDate.getUTCFullYear() }] : [])));
  const withBalances = rows.map((r) => {
    const b = r.leaveTypeId && r.fromDate ? found.get(balanceKey(r.studentProfileId, r.leaveTypeId, r.fromDate.getUTCFullYear())) ?? null : null;
    return { ...r, balance: b };
  });
  return pagination ? paginated(withBalances, total, pagination) : withBalances;
}

/**
 * Decide the step a leave is at. The hostel step needs MANAGE_STUDENTS; the
 * plant step needs APPROVE_PLANT_LEAVE for the employee's department (the
 * hostel admin can stand in for any). Approving the hostel step sends it to
 * the plant when the type asks for that and the department has an approver;
 * otherwise, or after the plant, the leave is approved.
 */
export async function decide(id: string, viewer: Approver, decision: 'APPROVE' | 'REJECT', note?: string) {
  const r = await db.studentRequest.findFirst({ where: { id }, include: { leaveType: true, student: { select: { departmentId: true, user: { select: { id: true } } } } } });
  if (!r || r.type !== StudentRequestType.LEAVE || !r.leaveTypeId) throw new NotFoundError('Leave not found');
  if (!OPEN.includes(r.status)) throw new ConflictError('This leave has already been decided');
  const tenantId = getTenantIdOrThrow();
  const now = new Date();

  if (r.leaveStage === 'PLANT') {
    if (!viewer.perms.includes('APPROVE_PLANT_LEAVE')) throw new ForbiddenError('This leave is waiting for the plant');
    if (viewer.role !== Role.HOSTEL_ADMIN) {
      const mine = await departmentsApprovedBy(viewer.userId);
      if (!r.student.departmentId || !mine.includes(r.student.departmentId)) throw new ForbiddenError('You do not approve leave for this department');
    }
    if (decision === 'REJECT') return close(r.id, StudentRequestStatus.REJECTED, { plantApprovedById: viewer.userId, plantApprovedAt: now, decisionNote: note ?? null });
    await db.studentRequest.update({ where: { id }, data: { plantApprovedById: viewer.userId, plantApprovedAt: now, ...(note ? { decisionNote: note } : {}) } });
    return approve(r.id, viewer.userId);
  }

  if (!viewer.perms.includes('MANAGE_STUDENTS')) throw new ForbiddenError('Requires permission: MANAGE_STUDENTS');
  if (decision === 'REJECT') return close(r.id, StudentRequestStatus.REJECTED, { hostelApprovedById: viewer.userId, hostelApprovedAt: now, decisionNote: note ?? null });
  await db.studentRequest.update({ where: { id }, data: { hostelApprovedById: viewer.userId, hostelApprovedAt: now, ...(note ? { decisionNote: note } : {}) } });
  const approvers = r.leaveType?.needsPlantApproval && r.student.departmentId ? await db.departmentApprover.count({ where: { departmentId: r.student.departmentId } }) : 0;
  if (approvers > 0) {
    await db.studentRequest.update({ where: { id }, data: { leaveStage: 'PLANT', status: StudentRequestStatus.IN_PROGRESS } });
    inBackground('push: leave to plant', () => notifyLeavePlantPending(tenantId, id));
    if (r.status !== StudentRequestStatus.IN_PROGRESS) inBackground('push: leave status', () => notifyRequestUpdated(tenantId, id, { status: StudentRequestStatus.IN_PROGRESS }));
    return getLeave(id);
  }
  return approve(r.id, viewer.userId);
}

async function close(id: string, status: StudentRequestStatus, data: Prisma.StudentRequestUncheckedUpdateInput) {
  await db.studentRequest.update({ where: { id }, data: { ...data, status, leaveStage: 'DONE', resolvedAt: new Date() } });
  const tenantId = getTenantIdOrThrow();
  inBackground('push: leave decided', () => notifyRequestUpdated(tenantId, id, { status }));
  return getLeave(id);
}

/** Sprint 6 (TEPL): a leave approved at the plant and sent in by its HR system gets the same pass and meals off. */
export async function applyApprovalEffects(id: string, actorId: string) {
  const tenantId = getTenantIdOrThrow();
  const r = await db.studentRequest.findFirstOrThrow({ where: { id }, select: { studentProfileId: true, fromDate: true, toDate: true, halfDay: true } });
  if (await tenantHasFeature(tenantId, 'gate')) {
    await issuePass(id, {}, actorId).catch((err) => console.error('[leave] pass not issued:', err)); // eslint-disable-line no-console
  }
  if (!r.halfDay && r.fromDate && r.toDate && (await tenantHasFeature(tenantId, 'mess'))) {
    const rows: Prisma.MessMealOptOutCreateManyInput[] = [];
    for (let t = r.fromDate.getTime(); t <= r.toDate.getTime() && rows.length < 3 * 120; t += DAY_MS) {
      for (const meal of [Meal.BREAKFAST, Meal.LUNCH, Meal.DINNER]) rows.push({ tenantId, studentProfileId: r.studentProfileId, date: new Date(t), meal });
    }
    if (rows.length) await db.messMealOptOut.createMany({ data: rows, skipDuplicates: true });
  }
}

/** The final yes: the gate pass, and no meals cooked for them while they are away. */
async function approve(id: string, actorId: string) {
  await close(id, StudentRequestStatus.APPROVED, {});
  const tenantId = getTenantIdOrThrow();
  const r = await db.studentRequest.findFirstOrThrow({ where: { id }, select: { studentProfileId: true, fromDate: true, toDate: true, halfDay: true } });
  if (await tenantHasFeature(tenantId, 'gate')) {
    await issuePass(id, {}, actorId).catch((err) => console.error('[leave] pass not issued:', err)); // eslint-disable-line no-console
  }
  if (!r.halfDay && r.fromDate && r.toDate && (await tenantHasFeature(tenantId, 'mess'))) {
    const rows: Prisma.MessMealOptOutCreateManyInput[] = [];
    for (let t = r.fromDate.getTime(); t <= r.toDate.getTime() && rows.length < 3 * 120; t += DAY_MS) {
      for (const meal of [Meal.BREAKFAST, Meal.LUNCH, Meal.DINNER]) rows.push({ tenantId, studentProfileId: r.studentProfileId, date: new Date(t), meal });
    }
    if (rows.length) await db.messMealOptOut.createMany({ data: rows, skipDuplicates: true });
  }
  return getLeave(id);
}

// ── The calendar ────────────────────────────────────────────────────────────

/** Leave touching [from, to]: approved and waiting, with or without a type. */
export async function calendar(from: Date, to: Date, filters: { propertyId?: string; departmentId?: string }) {
  if (to < from) throw new BadRequestError('The range ends before it starts');
  if (to.getTime() - from.getTime() > 62 * DAY_MS) throw new BadRequestError('Up to two months at a time');
  return db.studentRequest.findMany({
    where: {
      type: StudentRequestType.LEAVE,
      status: { in: [...OPEN, StudentRequestStatus.APPROVED] },
      fromDate: { lte: to },
      toDate: { gte: from },
      ...(filters.propertyId || filters.departmentId ? { student: { ...(filters.propertyId ? { propertyId: filters.propertyId } : {}), ...(filters.departmentId ? { departmentId: filters.departmentId } : {}) } } : {}),
    },
    include: leaveInclude,
    orderBy: { fromDate: 'asc' },
    take: 1000,
  });
}

/** The employee's own leave, newest first. */
export async function myLeaves(userId: string) {
  const profileId = await profileOf(userId);
  return db.studentRequest.findMany({ where: { studentProfileId: profileId, type: StudentRequestType.LEAVE }, include: leaveInclude, orderBy: { fromDate: 'desc' }, take: 50 });
}
