"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.DepartmentsService = 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 config_1 = require("../../config");
const utils_1 = require("../../utils");
const departments_dto_1 = require("./departments.dto");
let DepartmentsService = class DepartmentsService {
    constructor(db, permissionResolver) {
        this.db = db;
        this.permissionResolver = permissionResolver;
    }
    async assertGeneralAccess(ctx, manage = false) {
        const permissions = await this.permissionResolver.resolveForUser(ctx);
        (0, permission_resolver_helpers_1.assertGeneralModuleAccess)(permissions, manage);
    }
    async createDepartment(data, owner_id, ctx) {
        try {
            await this.assertGeneralAccess(ctx, true);
            const existingDepartment = await this.db.departments.findFirst({
                where: {
                    department_code: data.department_code,
                    owner_id,
                    status: (0, typeorm_1.Not)('deleted'),
                },
            });
            if (existingDepartment) {
                throw (0, utils_1.createGeneralError)('Department with same name or code already exists', 'department_code', common_1.HttpStatus.CONFLICT);
            }
            const deletedDepartment = await this.db.departments.findFirst({
                where: {
                    department_code: data.department_code,
                    owner_id,
                    status: 'deleted',
                },
            });
            if (deletedDepartment) {
                const restoredDepartment = await this.db.departments.update({
                    where: { id: deletedDepartment.id },
                    data: {
                        name: data.name,
                        department_code: data.department_code,
                        description: data.description ?? 'NT/APL',
                        status: data.status ?? 'active',
                        department_head_id: data.department_head_id ?? null,
                    },
                });
                const { data: parsedDepartment } = departments_dto_1.departmentResponseSchema.safeParse(restoredDepartment);
                return {
                    data: parsedDepartment,
                    message: 'Department created successfully',
                    status: common_1.HttpStatus.CREATED,
                    details: null,
                };
            }
            const department = await this.db.departments.create({
                data: {
                    name: data.name,
                    department_code: data.department_code,
                    ...(data.description ? { description: data.description } : {}),
                    ...(data.status ? { status: data.status } : {}),
                    ...(data.department_head_id
                        ? { department_head_id: data.department_head_id }
                        : {}),
                    owner_id,
                },
            });
            const { data: parsedDepartment } = departments_dto_1.departmentResponseSchema.safeParse(department);
            return {
                data: parsedDepartment,
                message: 'Department created successfully',
                status: common_1.HttpStatus.CREATED,
                details: null,
            };
        }
        catch (error) {
            config_1.logger.error(`Error in createDepartment: ${String(error)}`);
            if (error instanceof config_1.ErrorResponse) {
                throw error;
            }
            throw (0, utils_1.createGeneralError)(String(error), 'root', common_1.HttpStatus.BAD_REQUEST);
        }
    }
    async getDepartments(owner_id, ctx) {
        try {
            await this.assertGeneralAccess(ctx);
            const departments = await this.db.departments.findMany({
                orderBy: { created_at: 'asc' },
                where: {
                    owner_id,
                    status: (0, typeorm_1.Not)('deleted'),
                },
                include: {
                    _count: {
                        select: {
                            members: true,
                        },
                    },
                },
            });
            const departmentList = departments.map(({ _count, ...department }) => ({
                ...department,
                members_count: _count?.members ?? 0,
            }));
            const { data: parsedDepartments } = departments_dto_1.departmentsResponseSchema.safeParse(departmentList);
            return {
                data: parsedDepartments,
                message: 'Departments retrieved successfully',
                status: common_1.HttpStatus.OK,
                details: null,
            };
        }
        catch (error) {
            config_1.logger.error(`Error in getDepartments: ${String(error)}`);
            if (error instanceof config_1.ErrorResponse) {
                throw error;
            }
            throw (0, utils_1.createGeneralError)(String(error), 'root', common_1.HttpStatus.BAD_REQUEST);
        }
    }
    async getFilteredDepartments(owner_id, query, ctx) {
        try {
            await this.assertGeneralAccess(ctx);
            const page = query.page ?? 1;
            const limit = query.limit ?? 10;
            const skip = (page - 1) * limit;
            const baseWhere = {
                owner_id,
                status: (0, typeorm_1.Not)('deleted'),
            };
            if (query.search) {
                baseWhere.OR = [
                    { name: { contains: query.search } },
                    { department_code: { contains: query.search } },
                ];
            }
            const [departments, total] = await Promise.all([
                this.db.departments.findMany({
                    where: baseWhere,
                    include: {
                        department_head: true,
                        _count: {
                            select: {
                                members: true,
                            },
                        },
                    },
                    orderBy: { created_at: 'asc' },
                    skip,
                    take: limit,
                }),
                this.db.departments.count({ where: baseWhere }),
            ]);
            const departmentList = departments.map(({ _count, ...department }) => ({
                ...department,
                members_count: _count?.members ?? 0,
            }));
            const { data: parsedDepartments, error } = departments_dto_1.departmentsResponseSchema.safeParse(departmentList);
            const totalPages = Math.ceil(total / limit);
            return {
                data: parsedDepartments,
                message: 'Departments retrieved successfully',
                status: common_1.HttpStatus.OK,
                details: {
                    pagination: {
                        total_items: total,
                        total_pages: totalPages,
                        current_page: page,
                        items_per_page: limit,
                        has_next_page: page < totalPages,
                        has_previous_page: page > 1,
                        next_page: page < totalPages ? page + 1 : null,
                        previous_page: page > 1 ? page - 1 : null,
                    },
                },
            };
        }
        catch (error) {
            config_1.logger.error(`Error in getFilteredDepartments: ${String(error)}`);
            if (error instanceof config_1.ErrorResponse) {
                throw error;
            }
            throw (0, utils_1.createGeneralError)(String(error), 'root', common_1.HttpStatus.BAD_REQUEST);
        }
    }
    async getDepartmentById(id, owner_id, ctx) {
        try {
            await this.assertGeneralAccess(ctx);
            const department = await this.db.departments.findUnique({
                where: { id, owner_id },
                include: {
                    department_head: true,
                },
            });
            if (!department) {
                throw (0, utils_1.createGeneralError)('Department not found', 'department', common_1.HttpStatus.NOT_FOUND);
            }
            const parsedDepartment = {
                ...department,
                department_head: department.department_head
                    ? {
                        employee_id: department.department_head.employee_id,
                        nickname: department.department_head.nickname,
                        first_name: department.department_head.first_name,
                        last_name: department.department_head.last_name,
                        image: department.department_head.image,
                        role: department.department_head.role,
                    }
                    : null,
            };
            const { data: validatedDepartment } = departments_dto_1.departmentResponseSchema.safeParse(parsedDepartment);
            return {
                data: validatedDepartment,
                message: 'Department retrieved successfully',
                status: common_1.HttpStatus.OK,
                details: null,
            };
        }
        catch (error) {
            config_1.logger.error(`Error in getDepartmentById: ${String(error)}`);
            if (error instanceof config_1.ErrorResponse) {
                throw error;
            }
            throw (0, utils_1.createGeneralError)(String(error), 'root', common_1.HttpStatus.BAD_REQUEST);
        }
    }
    async updateDepartment(id, data, owner_id, ctx) {
        try {
            await this.assertGeneralAccess(ctx, true);
            const existingDepartment = await this.db.departments.findUnique({
                where: { id, owner_id },
            });
            if (!existingDepartment) {
                throw (0, utils_1.createGeneralError)('Department not found', 'department', common_1.HttpStatus.NOT_FOUND);
            }
            const { department_head_id, ...rest } = data;
            const updatedDepartment = await this.db.departments.update({
                where: { id, owner_id },
                data: {
                    ...rest,
                    ...(typeof department_head_id === 'string'
                        ? { department_head_id }
                        : department_head_id === null
                            ? { department_head_id: null }
                            : {}),
                },
                include: {
                    department_head: true,
                    members: true,
                },
            });
            const { data: parsedDepartment } = departments_dto_1.departmentResponseSchema.safeParse(updatedDepartment);
            return {
                data: parsedDepartment,
                message: 'Department updated successfully',
                status: common_1.HttpStatus.OK,
                details: null,
            };
        }
        catch (error) {
            config_1.logger.error(`Error in updateDepartment: ${String(error)}`);
            if (error instanceof config_1.ErrorResponse) {
                throw error;
            }
            throw (0, utils_1.createGeneralError)(String(error), 'root', common_1.HttpStatus.BAD_REQUEST);
        }
    }
    async deleteDepartment(id, owner_id, ctx) {
        try {
            await this.assertGeneralAccess(ctx, true);
            const existingDepartment = await this.db.departments.findUnique({
                where: { id, owner_id },
            });
            if (!existingDepartment) {
                throw (0, utils_1.createGeneralError)('Department not found', 'department', common_1.HttpStatus.NOT_FOUND);
            }
            const usageCount = await this.db.members.count({
                where: { department_id: id, owner_id },
            });
            if (usageCount > 0) {
                await this.db.departments.update({
                    where: { id, owner_id },
                    data: { status: 'deleted' },
                });
                return {
                    data: null,
                    message: 'Department is in use. Status changed to deleted.',
                    status: common_1.HttpStatus.OK,
                    details: {
                        usedByMembers: usageCount,
                    },
                };
            }
            await this.db.departments.delete({
                where: { id, owner_id },
            });
            return {
                data: null,
                message: 'Department deleted successfully',
                status: common_1.HttpStatus.OK,
                details: null,
            };
        }
        catch (error) {
            config_1.logger.error(`Error in deleteDepartment: ${String(error)}`);
            if (error instanceof config_1.ErrorResponse) {
                throw error;
            }
            throw (0, utils_1.createGeneralError)(String(error), 'root', common_1.HttpStatus.BAD_REQUEST);
        }
    }
};
exports.DepartmentsService = DepartmentsService;
exports.DepartmentsService = DepartmentsService = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [config_1.DatabaseService,
        permission_resolver_service_1.PermissionResolverService])
], DepartmentsService);
//# sourceMappingURL=departments.service.js.map