import { HttpStatus, Injectable } from '@nestjs/common';
import { Between, In, LessThanOrEqual, MoreThanOrEqual } from 'typeorm';
import { PermissionUserContext } from '../../common/access-control/permission-context.types';
import {
  assertToggle,
  buildMemberFilter,
  resolveDataScope,
} from '../../common/access-control/permission-resolver.helpers';
import { PermissionResolverService } from '../../common/access-control/permission-resolver.service';
import { OrgTimezoneService } from '../../common/timezone/org-timezone.service';
import { DatabaseService, ErrorResponse, logger } from '../../config';
import {
  createGeneralError,
  getCurrentMonthHolidays,
  getUtcMonthStartEndFromDate,
  getUtcStartEndOfDate,
  getUtcWeekStartEndFromDate,
  isGroupedAbsent,
  isGroupedPresent,
} from '../../utils';
import {
  countHolidayFromStartAndEnd,
  getAttendanceCountFromStartAndEnd,
  getAttendanceDetailsCountFromStartAndEnd,
  getCurrentWeekDetails,
  getLeaveCountFromStartAndEnd,
  getTotalWorkingDayFromStartAndEnd,
} from '../../utils/dashboard';
import { leavesResponseSchema } from '../leaves/leaves.dto';

@Injectable()
export class DashboardService {
  constructor(
    private readonly db: DatabaseService,
    private readonly permissionResolver: PermissionResolverService,
    private readonly orgTimezone: OrgTimezoneService,
  ) {}

  private async getPermissions(ctx: PermissionUserContext) {
    return this.permissionResolver.resolveForUser(ctx);
  }

  // async getSummary(owner_id: string, member_id: string, role: string) {
  //   try {
  //     const today = new Date();
  //     const { startUtc, endUtc } = getUtcStartEndOfDate(today);
  //     const { startUtc: monthStartUtc, endUtc: monthEndUtc } =
  //       getUtcMonthStartEndFromDate(today);
  //     const isMember = role === 'member';
  //     const member = isMember
  //       ? await this.db.members.findUnique({
  //           where: { id: member_id, owner_id },
  //           select: { department_id: true },
  //         })
  //       : null;
  //     const todayAttendance =
  //       role !== 'owner'
  //         ? await this.db.attendances.findFirst({
  //             where: {
  //               member_id,
  //               date: Between(startUtc, endUtc),
  //             },
  //           })
  //         : null;
  //     const todayAttendanceCount = !isMember
  //       ? await this.db.attendances.count({
  //           where: {
  //             owner_id,
  //             date: Between(startUtc, endUtc),
  //             status: Not('absent'),
  //           },
  //         })
  //       : 0;

  //     logger.error(
  //       `todayAttendanceCount: ${todayAttendanceCount} start_date ${startUtc}, end_date ${endUtc}`,
  //     );

  //     const todayPendingLeaveCount = !isMember
  //       ? await this.db.leaves.count({
  //           where: {
  //             owner_id,
  //             status: 'pending',
  //             start_date: Between(startUtc, endUtc),
  //           },
  //         })
  //       : 0;

  //     const totalMembers = isMember
  //       ? 1
  //       : await this.db.members.count({
  //           where: { owner_id, status: 'active' },
  //         });

  //     const attnDates = Between(monthStartUtc, endUtc);
  //     const leaveDates = Between(monthStartUtc, monthEndUtc);

  //     const nonRecurringHolidayWhere: any = {
  //       owner_id,
  //       is_recurring: false,
  //       start_date: attnDates,
  //     };

  //     const recurringHolidayWhere: any = {
  //       owner_id,
  //       is_recurring: true,
  //     };

  //     if (isMember && member?.department_id) {
  //       recurringHolidayWhere.departments = {
  //         some: {
  //           id: member.department_id,
  //         },
  //       };
  //       nonRecurringHolidayWhere.departments = {
  //         some: {
  //           id: member.department_id,
  //         },
  //       };
  //     }

  //     const [
  //       workSchedule,
  //       nonRecurringHolidays,
  //       recurringHolidays,
  //       attendances,
  //       leaves,
  //     ] = await Promise.all([
  //       this.db.working_schedule.findFirst({
  //         where: { owner_id },
  //       }),
  //       this.db.holidays.findMany({
  //         where: nonRecurringHolidayWhere,
  //         include: {
  //           departments: true,
  //         },
  //       }),
  //       this.db.holidays.findMany({
  //         where: recurringHolidayWhere,
  //       }),
  //       this.db.attendances.findMany({
  //         where: {
  //           owner_id,
  //           date: attnDates,
  //           status: In([
  //             'present',
  //             'check_in',
  //             'remote',
  //             'late',
  //             'half_day',
  //             'on_break',
  //             'on_leave',
  //           ]),
  //           ...(isMember ? { member_id } : {}),
  //         },
  //         orderBy: {
  //           date: 'desc',
  //         },
  //       }),
  //       this.db.leaves.findMany({
  //         where: {
  //           owner_id,
  //           status: 'approved',
  //           ...(leaveDates && { start_date: leaveDates }),
  //           ...(isMember && { member_id: member.id }),
  //         },
  //       }),
  //     ]);

  //     const holidays = getCurrentMonthHolidays(
  //       recurringHolidays,
  //       nonRecurringHolidays,
  //       monthStartUtc,
  //       endUtc,
  //     );

  //     const holidayCount = countHolidayFromStartAndEnd(
  //       holidays,
  //       workSchedule,
  //       monthStartUtc,
  //       endUtc,
  //     );

  //     const thisWeekLeaveCount = getLeaveCountFromStartAndEnd(
  //       leaves,
  //       workSchedule,
  //       monthStartUtc,
  //       endUtc,
  //     );

  //     const workingDayCount = getTotalWorkingDayFromStartAndEnd(
  //       holidays,
  //       workSchedule,
  //       monthStartUtc,
  //       endUtc,
  //     );

  //     const attendanceCountInRange = getAttendanceCountFromStartAndEnd(
  //       attendances,
  //       monthStartUtc,
  //       endUtc,
  //       startUtc,
  //     );
  //     const absentCount = isMember
  //       ? Math.max(
  //           0,
  //           workingDayCount - thisWeekLeaveCount - attendanceCountInRange,
  //         )
  //       : Math.max(
  //           0,
  //           workingDayCount * totalMembers -
  //             thisWeekLeaveCount -
  //             attendanceCountInRange,
  //         );

  //     const todayLeaveCount = getLeaveCountFromStartAndEnd(
  //       leaves,
  //       workSchedule,
  //       startUtc,
  //       endUtc,
  //     );

  //     const todayAbsentCount = isMember
  //       ? Math.max(0, 1 - todayLeaveCount - todayAttendanceCount)
  //       : Math.max(0, totalMembers - todayLeaveCount - todayAttendanceCount);

  //     const { isHoliday, isWeekend } = getIsTodayWeekend(
  //       holidays,
  //       workSchedule,
  //       today,
  //     );
  //     const todayStatus = todayAttendance
  //       ? todayAttendance?.status
  //       : isHoliday || isWeekend
  //         ? isHoliday
  //           ? 'holiday'
  //           : 'weekend'
  //         : 'absent';

  //     return {
  //       data: {
  //         total_members: totalMembers,
  //         today_status: todayStatus,
  //         present_days: attendanceCountInRange,
  //         leave_days: leaves?.length ?? 0,
  //         absent_days: absentCount,
  //         this_week_leave_days: thisWeekLeaveCount,
  //         this_week_holidays: holidayCount,
  //         today_pending_leaves: todayPendingLeaveCount,
  //         today_absent_count: todayAbsentCount,
  //         today_leave_count: todayLeaveCount,
  //         today_present_count: todayAttendanceCount,
  //       },
  //       details: null,
  //       status: HttpStatus.OK,
  //       message: 'Summary fetched successfully',
  //     };
  //   } catch (error) {
  //     logger.error(`Error in getSummary: ${String(error)}`);
  //     if (error instanceof ErrorResponse) throw error;
  //     throw createGeneralError(String(error), 'root', HttpStatus.BAD_REQUEST);
  //   }
  // }

  async getThisWeeks(
    owner_id: string,
    ctx: PermissionUserContext,
    dataScope?: 'own' | 'all',
  ) {
    try {
      const timeZone = await this.orgTimezone.getTimezone(owner_id);
      const permissions = await this.getPermissions(ctx);
      assertToggle(permissions, 'dashboard.access');
      const scopeFilter = resolveDataScope(
        permissions,
        'dashboard.view',
        dataScope,
        ctx,
      );
      const isOwnData = scopeFilter === 'own';
      const member_id = ctx.sub;

      const today = new Date();
      const { startUtc, endUtc } = getUtcStartEndOfDate(today, timeZone);

      const { startUtc: weekStartUtc, endUtc: weekEndUtc } =
        getUtcWeekStartEndFromDate(today, timeZone);
      const calculationEndUtc = endUtc < weekEndUtc ? endUtc : weekEndUtc;
      const member = isOwnData
        ? await this.db.members.findUnique({
            where: { id: member_id, owner_id },
            select: { department_id: true },
          })
        : null;
      const totalMembers = isOwnData
        ? 1
        : await this.db.members.count({
            where: { owner_id, status: 'active' },
          });

      const nonRecurringHolidayWhere: any = {
        owner_id,
        is_recurring: false,
        start_date: LessThanOrEqual(calculationEndUtc),
        end_date: MoreThanOrEqual(weekStartUtc),
      };

      const recurringHolidayWhere: any = {
        owner_id,
        is_recurring: true,
      };

      if (isOwnData && member?.department_id) {
        recurringHolidayWhere.departments = {
          some: {
            id: member.department_id,
          },
        };
        nonRecurringHolidayWhere.departments = {
          some: {
            id: member.department_id,
          },
        };
      }

      const [
        workSchedule,
        nonRecurringHolidays,
        recurringHolidays,
        attendances,
        leaves,
      ] = await Promise.all([
        this.db.working_schedule.findFirst({
          where: { owner_id },
        }),
        this.db.holidays.findMany({
          where: nonRecurringHolidayWhere,
          include: {
            departments: true,
          },
        }),
        this.db.holidays.findMany({
          where: recurringHolidayWhere,
        }),
        this.db.attendances.findMany({
          where: {
            owner_id,
            date: Between(weekStartUtc, calculationEndUtc),
            status: In([
              'present',
              'check_in',
              'remote',
              'late',
              'half_day',
              'on_break',
              'on_leave',
            ]),
            ...(isOwnData ? { member_id } : {}),
          },
          orderBy: {
            date: 'desc',
          },
        }),
        this.db.leaves.findMany({
          where: {
            owner_id,
            status: 'approved',
            start_date: LessThanOrEqual(calculationEndUtc),
            end_date: MoreThanOrEqual(weekStartUtc),
            ...(isOwnData && { member_id: member.id }),
          },
        }),
      ]);

      const holidays = getCurrentMonthHolidays(
        recurringHolidays,
        nonRecurringHolidays,
        weekStartUtc,
        weekEndUtc,
      );

      const weekDetails = getCurrentWeekDetails(
        weekStartUtc,
        weekEndUtc,
        holidays,
        leaves,
        workSchedule,
      );

      const thisWeekLeaveCount = getLeaveCountFromStartAndEnd(
        leaves,
        workSchedule,
        weekStartUtc,
        calculationEndUtc,
      );

      const workingDayCount = getTotalWorkingDayFromStartAndEnd(
        holidays,
        workSchedule,
        weekStartUtc,
        calculationEndUtc,
      );

      const { attendance_count, late_count, half_day_count } =
        getAttendanceDetailsCountFromStartAndEnd(
          attendances,
          weekStartUtc,
          calculationEndUtc,
          startUtc,
        );

      const absentCount = isOwnData
        ? Math.max(
            0,
            workingDayCount -
              thisWeekLeaveCount -
              attendance_count -
              late_count -
              half_day_count,
          )
        : Math.max(
            0,
            workingDayCount * totalMembers -
              thisWeekLeaveCount -
              attendance_count -
              late_count -
              half_day_count,
          );

      return {
        data: weekDetails,
        details: {
          present: attendance_count,
          late: late_count,
          half_day: half_day_count,
          absent: absentCount,
          leave: thisWeekLeaveCount,
        },
        status: HttpStatus.OK,
        message: 'This week summary fetched successfully',
      };
    } catch (error) {
      logger.error(`Error in getThisWeeks: ${String(error)}`);
      if (error instanceof ErrorResponse) throw error;
      throw createGeneralError(String(error), 'root', HttpStatus.BAD_REQUEST);
    }
  }

  async getSummary(
    owner_id: string,
    ctx: PermissionUserContext,
    dataScope?: 'own' | 'all',
  ) {
    try {
      const timeZone = await this.orgTimezone.getTimezone(owner_id);
      const permissions = await this.getPermissions(ctx);
      assertToggle(permissions, 'dashboard.access');
      const scopeFilter = resolveDataScope(
        permissions,
        'dashboard.view',
        dataScope,
        ctx,
      );
      const isOwnData = scopeFilter === 'own';
      const member_id = ctx.sub;

      const today = new Date();
      const { startUtc, endUtc } = getUtcStartEndOfDate(today, timeZone);
      const { startUtc: monthStartUtc, endUtc: monthEndUtc } =
        getUtcMonthStartEndFromDate(today, timeZone);
      const isMember = isOwnData;

      const summaryData = {
        total_members: 0,
        today_status: 'absent',
        present_days: 0,
        leave_days: 0,
        absent_days: 0,
        this_week_leave_days: 0,
        this_week_holidays: 0,
        today_pending_leaves: 0,
        today_absent_count: 0,
        today_leave_count: 0,
        today_present_count: 0,
      };

      if (isMember) {
        const [attendances, leaves, work_schedule] = await Promise.all([
          this.db.attendances.findMany({
            where: {
              member_id,
              date: Between(monthStartUtc, monthEndUtc),
            },
          }),
          this.db.leaves.findMany({
            where: {
              member_id,
              status: 'approved',
              start_date: Between(monthStartUtc, monthEndUtc),
            },
          }),
          this.db.working_schedule.findFirst({
            where: { owner_id },
          }),
        ]);

        attendances.forEach((attendance) => {
          const isToday =
            attendance.date >= startUtc && attendance.date <= endUtc;
          if (isToday) {
            summaryData.today_status = attendance.status;
          }

          if (isGroupedPresent(attendance.status, isToday)) {
            summaryData.present_days += 1;
          } else if (isGroupedAbsent(attendance.status, isToday)) {
            summaryData.absent_days += 1;
          }
        });

        summaryData.leave_days = getLeaveCountFromStartAndEnd(
          leaves,
          work_schedule,
          monthStartUtc,
          monthEndUtc,
          false,
        );
      } else {
        const [memberCount, todayAttendances] = await Promise.all([
          this.db.members.count({
            where: { owner_id, status: 'active' },
          }),
          this.db.attendances.findMany({
            where: {
              owner_id,
              date: Between(startUtc, endUtc),
            },
          }),
        ]);

        summaryData.total_members = memberCount;
        todayAttendances.forEach((attendance) => {
          if (isGroupedPresent(attendance.status, true)) {
            summaryData.today_present_count += 1;
          } else if (attendance.status === 'on_leave') {
            summaryData.today_leave_count += 1;
          } else if (attendance.status === 'absent') {
            summaryData.today_absent_count += 1;
          }
        });
      }

      return {
        data: summaryData,
        details: null,
        status: HttpStatus.OK,
        message: 'Summary fetched successfully',
      };
    } catch (error) {
      logger.error(`Error in getSummary: ${String(error)}`);
      if (error instanceof ErrorResponse) throw error;
      throw createGeneralError(String(error), 'root', HttpStatus.BAD_REQUEST);
    }
  }

  // async getThisWeeks(owner_id: string, member_id: string, role: string) {
  //   try {
  //     const today = new Date();
  //     const { startUtc, endUtc } = getUtcStartEndOfDate(today);
  //     const { startUtc: weekStartUtc, endUtc: weekEndUtc } =
  //       getUtcWeekStartEndFromDate(today);
  //     const isOwner = role === 'owner';
  //     const workSchedule = await this.db.working_schedule.findFirst({
  //       where: { owner_id },
  //     });

  //     if (isOwner) {
  //       const weekDetails = getCurrentWeekDetails(
  //         weekStartUtc,
  //         weekEndUtc,
  //         [],
  //         workSchedule,
  //       );

  //       const todayAttendances = await this.db.attendances.findMany({
  //         where: {
  //           owner_id,
  //           date: Between(weekStartUtc, weekEndUtc),
  //         },
  //       });

  //       const summary = todayAttendances.reduce(
  //         (acc, attendance) => {
  //           const isToday =
  //             attendance.date >= startUtc && attendance.date <= endUtc;
  //           if (
  //             isToday &&
  //             presentExceptionStatuses.includes(attendance.status as any)
  //           ) {
  //             acc.present += 1;
  //           } else if (attendance.status === 'late') {
  //             acc.late += 1;
  //           } else if (attendance.status === 'half_day') {
  //             acc.half_day += 1;
  //           } else if (attendance.status === 'on_leave') {
  //             acc.leave += 1;
  //           } else if (attendance.status === 'absent') {
  //             acc.absent += 1;
  //           }
  //           return acc;
  //         },
  //         {
  //           present: 0,
  //           late: 0,
  //           half_day: 0,
  //           absent: 0,
  //           leave: 0,
  //         },
  //       );

  //       return {
  //         data: weekDetails,
  //         details: summary,
  //         status: HttpStatus.OK,
  //         message: 'This week summary fetched successfully',
  //       };
  //     } else {
  //       const attendances = await this.db.attendances.findMany({
  //         where: {
  //           owner_id,
  //           member_id,
  //           date: Between(weekStartUtc, weekEndUtc),
  //         },
  //         orderBy: {
  //           date: 'desc',
  //         },
  //       });

  //       const weekDetails = getCurrentWeekDetails(
  //         weekStartUtc,
  //         weekEndUtc,
  //         attendances,
  //         workSchedule,
  //       );

  //       const summaryData = {
  //         present: 0,
  //         late: 0,
  //         half_day: 0,
  //         absent: 0,
  //         leave: 0,
  //         weekend: 0,
  //         holiday: 0,
  //       };

  //       attendances.forEach((attendance) => {
  //         const isToday =
  //           attendance.date >= startUtc && attendance.date <= endUtc;
  //         if (
  //           attendance.status === 'present' ||
  //           (isToday &&
  //             presentExceptionStatuses.includes(attendance.status as any))
  //         ) {
  //           summaryData.present += 1;
  //         } else if (attendance.status === 'late') {
  //           summaryData.late += 1;
  //         } else if (attendance.status === 'half_day') {
  //           summaryData.half_day += 1;
  //         } else if (attendance.status === 'on_leave') {
  //           summaryData.leave += 1;
  //         } else if (
  //           attendance.status === 'absent' ||
  //           (!isToday &&
  //             presentExceptionStatuses.includes(attendance.status as any))
  //         ) {
  //           summaryData.absent += 1;
  //         } else if (attendance.status === 'weekend') {
  //           summaryData.weekend += 1;
  //         } else if (attendance.status === 'holiday') {
  //           summaryData.holiday += 1;
  //         }
  //       });

  //       return {
  //         data: weekDetails,
  //         details: summaryData,
  //         status: HttpStatus.OK,
  //         message: 'This week summary fetched successfully',
  //       };
  //     }
  //   } catch (error) {
  //     logger.error(`Error in getThisWeeks: ${String(error)}`);
  //     if (error instanceof ErrorResponse) throw error;
  //     throw createGeneralError(String(error), 'root', HttpStatus.BAD_REQUEST);
  //   }
  // }

  async getThisMonthReport(
    owner_id: string,
    ctx: PermissionUserContext,
    dataScope?: 'own' | 'all',
  ) {
    try {
      const timeZone = await this.orgTimezone.getTimezone(owner_id);
      const permissions = await this.getPermissions(ctx);
      assertToggle(permissions, 'dashboard.access');
      const scopeFilter = resolveDataScope(
        permissions,
        'dashboard.view',
        dataScope,
        ctx,
      );
      const isMember = scopeFilter === 'own';
      const member_id = ctx.sub;

      const today = new Date();
      const { startUtc: todayStartUtc } = getUtcStartEndOfDate(today, timeZone);
      const { startUtc, endUtc } = getUtcMonthStartEndFromDate(today, timeZone);
      const member = isMember
        ? await this.db.members.findUnique({
            where: { id: member_id, owner_id },
            select: { department_id: true },
          })
        : null;

      const totalMembers = isMember
        ? 1
        : await this.db.members.count({
            where: { owner_id, status: 'active' },
          });

      const asnDates = Between(startUtc, endUtc);

      const nonRecurringHolidayWhere: any = {
        owner_id,
        is_recurring: false,
        start_date: asnDates,
      };

      const recurringHolidayWhere: any = {
        owner_id,
        is_recurring: true,
      };

      if (isMember && member?.department_id) {
        recurringHolidayWhere.departments = {
          some: {
            id: member.department_id,
          },
        };
        nonRecurringHolidayWhere.departments = {
          some: {
            id: member.department_id,
          },
        };
      }

      const [
        workSchedule,
        nonRecurringHolidays,
        recurringHolidays,
        attendances,
        leaves,
      ] = await Promise.all([
        this.db.working_schedule.findFirst({
          where: { owner_id },
        }),
        this.db.holidays.findMany({
          where: nonRecurringHolidayWhere,
          include: {
            departments: true,
          },
        }),
        this.db.holidays.findMany({
          where: recurringHolidayWhere,
        }),
        this.db.attendances.findMany({
          where: {
            owner_id,
            date: asnDates,
            status: In([
              'present',
              'check_in',
              'remote',
              'late',
              'half_day',
              'on_break',
              'on_leave',
            ]),
            ...(isMember ? { member_id } : {}),
          },
          orderBy: {
            date: 'desc',
          },
        }),
        this.db.leaves.findMany({
          where: {
            owner_id,
            status: 'approved',
            start_date: LessThanOrEqual(endUtc),
            end_date: MoreThanOrEqual(startUtc),
            ...(isMember && { member_id: member.id }),
          },
        }),
      ]);

      const holidays = getCurrentMonthHolidays(
        recurringHolidays,
        nonRecurringHolidays,
        startUtc,
        endUtc,
      );

      const holidayCount = countHolidayFromStartAndEnd(
        holidays,
        workSchedule,
        startUtc,
        endUtc,
      );

      const thisMonthLeaveCount = getLeaveCountFromStartAndEnd(
        leaves,
        workSchedule,
        startUtc,
        endUtc,
        false,
      );

      const workingDayCount = getTotalWorkingDayFromStartAndEnd(
        holidays,
        workSchedule,
        startUtc,
        endUtc,
      );

      const attendanceCountInRange = getAttendanceCountFromStartAndEnd(
        attendances,
        startUtc,
        endUtc,
        todayStartUtc,
      );

      const absentCount = isMember
        ? Math.max(
            0,
            workingDayCount - thisMonthLeaveCount - attendanceCountInRange,
          )
        : Math.max(
            0,
            workingDayCount * totalMembers -
              thisMonthLeaveCount -
              attendanceCountInRange,
          );

      const totalPossibleAttendance = workingDayCount * totalMembers;

      const attendancePercentage =
        totalPossibleAttendance === 0
          ? 0
          : Math.round(
              (attendanceCountInRange / totalPossibleAttendance) * 10000,
            ) / 100;

      logger.error(`attendanceCountInRange: ${workingDayCount}`);
      logger.error(`attendanceCountInRange: ${holidayCount}`);
      logger.error(`totalPossibleAttendance: ${totalPossibleAttendance}`);
      logger.error(`attendancePercentage: ${attendancePercentage}`);

      return {
        data: {
          attendance_percentage: attendancePercentage,
          working_days: workingDayCount,
          present_count: attendanceCountInRange,
          approved_leaves: thisMonthLeaveCount ?? 0,
          holidays: holidayCount,
          total_members: totalMembers,
          absent_count: absentCount,
        },
        details: null,
        status: HttpStatus.OK,
        message: 'This month summary fetched successfully',
      };
    } catch (error) {
      logger.error(`Error in getThisMonthReport: ${String(error)}`);
      if (error instanceof ErrorResponse) throw error;
      throw createGeneralError(String(error), 'root', HttpStatus.BAD_REQUEST);
    }
  }

  async getPendingLeaves(
    owner_id: string,
    ctx: PermissionUserContext,
    query: { data_scope?: 'own' | 'all'; page?: number; limit?: number },
  ) {
    try {
      const permissions = await this.getPermissions(ctx);
      assertToggle(permissions, 'dashboard.access');
      const scopeFilter = resolveDataScope(
        permissions,
        'dashboard.view',
        query.data_scope,
        ctx,
      );
      const memberFilter = buildMemberFilter(scopeFilter, ctx.sub);

      const page = query.page || 1;
      const limit = query.limit || 4;
      const skip = (page - 1) * limit;

      const where = {
        owner_id,
        status: 'pending' as const,
        ...memberFilter,
      };

      const leaves = await this.db.leaves.findMany({
        where,
        include: {
          member: {
            include: {
              department: true,
            },
          },
          approver_owner: true,
          approver_member: true,
        },
        orderBy: { created_at: 'desc' },
        skip,
        take: limit,
      });

      const { data: parsedLeaves } = leavesResponseSchema.safeParse(leaves);

      return {
        data: parsedLeaves,
        message: 'Pending leave requests retrieved successfully',
        status: HttpStatus.OK,
        details: null,
      };
    } catch (error) {
      logger.error(`Error in getPendingLeaves: ${String(error)}`);
      if (error instanceof ErrorResponse) {
        throw error;
      }
      throw createGeneralError(String(error), 'root', HttpStatus.BAD_REQUEST);
    }
  }
}
