"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CalendarService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("typeorm");
const permission_resolver_helpers_1 = require("../../common/access-control/permission-resolver.helpers");
const permission_resolver_service_1 = require("../../common/access-control/permission-resolver.service");
const org_timezone_service_1 = require("../../common/timezone/org-timezone.service");
const config_1 = require("../../config");
const utils_1 = require("../../utils");
const calendar_dto_1 = require("./calendar.dto");
let CalendarService = class CalendarService {
    constructor(db, permissionResolver, orgTimezone) {
        this.db = db;
        this.permissionResolver = permissionResolver;
        this.orgTimezone = orgTimezone;
    }
    async getPermissions(ctx) {
        return this.permissionResolver.resolveForUser(ctx);
    }
    async getMonthHistory(owner_id, ctx, month, year, dataScope) {
        try {
            const timeZone = await this.orgTimezone.getTimezone(owner_id);
            const permissions = await this.getPermissions(ctx);
            (0, permission_resolver_helpers_1.assertToggle)(permissions, 'calendar.access');
            const scopeFilter = (0, permission_resolver_helpers_1.resolveDataScope)(permissions, 'calendar.view', dataScope, ctx);
            const isMember = scopeFilter === 'own';
            const member_id = ctx.sub;
            const { startUtc, endUtc } = (0, utils_1.getUtcMonthStartEnd)(year, month, 6, timeZone);
            const member = isMember
                ? await this.db.members.findUnique({
                    where: {
                        id: member_id,
                        owner_id,
                    },
                    include: {
                        department: true,
                    },
                })
                : null;
            const asnDate = (0, typeorm_1.Between)(startUtc, endUtc);
            const noticeWhere = {
                owner_id,
                published_at: asnDate,
            };
            const nonRecurringHolidayWhere = {
                owner_id,
                is_recurring: false,
                start_date: {
                    lte: endUtc,
                },
                end_date: {
                    gte: startUtc,
                },
            };
            const recurringHolidayWhere = {
                owner_id,
                is_recurring: true,
            };
            if (isMember && member) {
                const orConditions = [
                    {
                        recipients: {
                            some: {
                                id: member_id,
                            },
                        },
                    },
                ];
                if (member.department_id) {
                    orConditions.push({
                        departments: {
                            some: {
                                id: member.department_id,
                            },
                        },
                    });
                    recurringHolidayWhere.departments = {
                        some: {
                            id: member.department_id,
                        },
                    };
                    nonRecurringHolidayWhere.departments = {
                        some: {
                            id: member.department_id,
                        },
                    };
                }
                noticeWhere.OR = orConditions;
            }
            const [attendances, notices, nonRecurringHolidays, recurringHolidays] = await Promise.all([
                this.db.attendances.findMany({
                    where: {
                        owner_id,
                        date: asnDate,
                        ...(isMember ? { member_id } : {}),
                    },
                    orderBy: {
                        date: 'desc',
                    },
                    include: {
                        member: true,
                    },
                }),
                this.db.notices.findMany({
                    where: noticeWhere,
                    include: {
                        departments: true,
                        recipients: true,
                    },
                    orderBy: {
                        published_at: 'desc',
                    },
                }),
                this.db.holidays.findMany({
                    where: nonRecurringHolidayWhere,
                    include: {
                        departments: true,
                    },
                }),
                this.db.holidays.findMany({
                    where: recurringHolidayWhere,
                    include: {
                        departments: true,
                    },
                }),
            ]);
            const holidays = (0, utils_1.getCurrentMonthHolidays)(recurringHolidays, nonRecurringHolidays, startUtc, endUtc, timeZone);
            const filteredNotices = notices?.map((item) => ({
                id: item.id,
                title: item.title,
                content: item?.content && item.content !== 'NT/APL' ? item.content : null,
                date: item.published_at,
                start_date: item.published_at,
                end_date: item?.expire_at ?? null,
                departments: item?.departments || [],
                department: null,
                status: item.status,
                image: null,
                name: 'Notice',
                type: 'notice',
                attendance_type: '',
                priority: item?.priority ?? 'medium',
                check_in: null,
                check_out: null,
                break_hours: null,
                total_working_hours: null,
                lunch_start: null,
                lunch_end: null,
                breaks: [],
                note: '',
            }));
            const filteredHolidays = holidays?.map((item) => ({
                id: item.id,
                title: item?.name ?? 'Holiday',
                content: item?.description ?? null,
                date: item?.start_date ?? null,
                start_date: item?.start_date ?? null,
                end_date: item?.end_date ?? null,
                departments: item?.departments || [],
                department: null,
                status: null,
                image: null,
                name: 'Holiday',
                type: 'holiday',
                attendance_type: '',
                check_in: null,
                check_out: null,
                break_hours: null,
                total_working_hours: null,
                lunch_start: null,
                lunch_end: null,
                breaks: [],
                note: '',
            }));
            const filteredAttendances = attendances?.map((item) => ({
                id: item.id,
                title: item?.member?.first_name && item?.member?.last_name
                    ? `${item.member.first_name} ${item.member.last_name}`
                    : 'Attendance',
                content: item?.note && item.note !== 'NT/APL' ? item.note : null,
                date: item?.date ?? null,
                start_date: item?.date ?? null,
                end_date: item?.date ?? null,
                departments: [],
                department: item?.member?.department ?? null,
                status: item?.status ?? null,
                image: item?.member?.image ?? null,
                name: 'Attendance',
                type: 'attendance',
                attendance_type: item?.type ?? '',
                priority: null,
                check_in: item?.check_in ?? null,
                check_out: item?.check_out ?? null,
                break_hours: item?.break_hours ?? null,
                total_working_hours: item?.work_hours ?? null,
                lunch_start: null,
                lunch_end: null,
                breaks: [],
                note: item?.note && item.note !== 'NT/APL' ? item.note : '',
            }));
            const history = [
                ...(filteredHolidays ?? []),
                ...(filteredAttendances ?? []),
                ...(filteredNotices ?? []),
            ];
            const { data: parsedData, error } = calendar_dto_1.monthHistoryResponseArraySchema.safeParse(history);
            console.log('Parsed data:', parsedData, error);
            return {
                data: parsedData ?? [],
                message: 'Calendar month history retrieved successfully',
                status: common_1.HttpStatus.OK,
                details: {
                    total: history.length,
                    month,
                    year,
                    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
                },
            };
        }
        catch (error) {
            config_1.logger.error(`Error in getSummary: ${String(error)}`);
            if (error instanceof config_1.ErrorResponse)
                throw error;
            throw (0, utils_1.createGeneralError)(String(error), 'root', common_1.HttpStatus.BAD_REQUEST);
        }
    }
};
exports.CalendarService = CalendarService;
exports.CalendarService = CalendarService = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [config_1.DatabaseService,
        permission_resolver_service_1.PermissionResolverService,
        org_timezone_service_1.OrgTimezoneService])
], CalendarService);
//# sourceMappingURL=calendar.service.js.map