"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.HiringSourcesService = void 0;
const common_1 = require("@nestjs/common");
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 hiring_sources_dto_1 = require("./hiring_sources.dto");
let HiringSourcesService = class HiringSourcesService {
    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 createHiringSource(data, owner_id, ctx) {
        try {
            await this.assertGeneralAccess(ctx, true);
            const existing = await this.db.hiring_sources.findFirst({
                where: {
                    name: data.name,
                    owner_id,
                },
            });
            if (existing) {
                throw (0, utils_1.createGeneralError)('Hiring source with same name already exists', 'name', common_1.HttpStatus.CONFLICT);
            }
            const hiringSource = await this.db.hiring_sources.create({
                data: {
                    name: data.name,
                    ...(data.description ? { description: data.description } : {}),
                    ...(data.status ? { status: data.status } : {}),
                    owner_id,
                },
            });
            const { data: parsed } = hiring_sources_dto_1.hiringSourceResponseSchema.safeParse(hiringSource);
            return {
                data: parsed,
                message: 'Hiring source created successfully',
                status: common_1.HttpStatus.CREATED,
                details: null,
            };
        }
        catch (error) {
            config_1.logger.error(`Error in createHiringSource: ${String(error)}`);
            if (error instanceof config_1.ErrorResponse)
                throw error;
            throw (0, utils_1.createGeneralError)(String(error), 'root', common_1.HttpStatus.BAD_REQUEST);
        }
    }
    async getHiringSources(owner_id, ctx) {
        try {
            await this.assertGeneralAccess(ctx);
            const hiringSources = await this.db.hiring_sources.findMany({
                where: {
                    owner_id,
                    status: {
                        not: 'deleted',
                    },
                },
                orderBy: { created_at: 'asc' },
            });
            const { data: parsed } = hiring_sources_dto_1.hiringSourcesResponseSchema.safeParse(hiringSources);
            return {
                data: parsed,
                message: 'Hiring sources retrieved successfully',
                status: common_1.HttpStatus.OK,
                details: null,
            };
        }
        catch (error) {
            config_1.logger.error(`Error in getHiringSources: ${String(error)}`);
            if (error instanceof config_1.ErrorResponse)
                throw error;
            throw (0, utils_1.createGeneralError)(String(error), 'root', common_1.HttpStatus.BAD_REQUEST);
        }
    }
    async getFilteredHiringSources(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 where = {
                owner_id,
                status: {
                    not: 'deleted',
                },
            };
            if (query.search) {
                where.OR = [{ name: { contains: query.search } }];
            }
            const [hiringSources, total] = await Promise.all([
                this.db.hiring_sources.findMany({
                    where,
                    orderBy: { created_at: 'asc' },
                    skip,
                    take: limit,
                }),
                this.db.hiring_sources.count({ where }),
            ]);
            const { data: parsed } = hiring_sources_dto_1.hiringSourcesResponseSchema.safeParse(hiringSources);
            const totalPages = Math.ceil(total / limit);
            return {
                data: parsed,
                message: 'Hiring sources 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 getFilteredHiringSources: ${String(error)}`);
            if (error instanceof config_1.ErrorResponse)
                throw error;
            throw (0, utils_1.createGeneralError)(String(error), 'root', common_1.HttpStatus.BAD_REQUEST);
        }
    }
    async getHiringSourceById(id, owner_id, ctx) {
        try {
            await this.assertGeneralAccess(ctx);
            const hiringSource = await this.db.hiring_sources.findUnique({
                where: { id, owner_id },
            });
            if (!hiringSource) {
                throw (0, utils_1.createGeneralError)('Hiring source not found', 'hiring_source', common_1.HttpStatus.NOT_FOUND);
            }
            const { data: parsed } = hiring_sources_dto_1.hiringSourceResponseSchema.safeParse(hiringSource);
            return {
                data: parsed,
                message: 'Hiring source retrieved successfully',
                status: common_1.HttpStatus.OK,
                details: null,
            };
        }
        catch (error) {
            config_1.logger.error(`Error in getHiringSourceById: ${String(error)}`);
            if (error instanceof config_1.ErrorResponse)
                throw error;
            throw (0, utils_1.createGeneralError)(String(error), 'root', common_1.HttpStatus.BAD_REQUEST);
        }
    }
    async updateHiringSource(id, data, owner_id, ctx) {
        try {
            await this.assertGeneralAccess(ctx, true);
            const existing = await this.db.hiring_sources.findUnique({
                where: { id, owner_id },
            });
            if (!existing) {
                throw (0, utils_1.createGeneralError)('Hiring source not found', 'hiring_source', common_1.HttpStatus.NOT_FOUND);
            }
            const updated = await this.db.hiring_sources.update({
                where: { id, owner_id },
                data,
            });
            const { data: parsed } = hiring_sources_dto_1.hiringSourceResponseSchema.safeParse(updated);
            return {
                data: parsed,
                message: 'Hiring source updated successfully',
                status: common_1.HttpStatus.OK,
                details: null,
            };
        }
        catch (error) {
            config_1.logger.error(`Error in updateHiringSource: ${String(error)}`);
            if (error instanceof config_1.ErrorResponse)
                throw error;
            throw (0, utils_1.createGeneralError)(String(error), 'root', common_1.HttpStatus.BAD_REQUEST);
        }
    }
    async deleteHiringSource(id, owner_id, ctx) {
        try {
            await this.assertGeneralAccess(ctx, true);
            const existing = await this.db.hiring_sources.findUnique({
                where: { id, owner_id },
            });
            if (!existing) {
                throw (0, utils_1.createGeneralError)('Hiring source not found', 'hiring_source', common_1.HttpStatus.NOT_FOUND);
            }
            const usageCount = await this.db.members.count({
                where: { hiring_source_id: id, owner_id },
            });
            if (usageCount > 0) {
                const softDeleted = await this.db.hiring_sources.update({
                    where: { id, owner_id },
                    data: {
                        status: 'deleted',
                    },
                });
                const { data: parsed } = hiring_sources_dto_1.hiringSourceResponseSchema.safeParse(softDeleted);
                return {
                    data: parsed,
                    message: 'Hiring source is in use. Status changed to deleted.',
                    status: common_1.HttpStatus.OK,
                    details: {
                        usedByMembers: usageCount,
                    },
                };
            }
            await this.db.hiring_sources.delete({
                where: { id, owner_id },
            });
            return {
                data: null,
                message: 'Hiring source deleted successfully',
                status: common_1.HttpStatus.OK,
                details: null,
            };
        }
        catch (error) {
            config_1.logger.error(`Error in deleteHiringSource: ${String(error)}`);
            if (error instanceof config_1.ErrorResponse)
                throw error;
            throw (0, utils_1.createGeneralError)(String(error), 'root', common_1.HttpStatus.BAD_REQUEST);
        }
    }
};
exports.HiringSourcesService = HiringSourcesService;
exports.HiringSourcesService = HiringSourcesService = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [config_1.DatabaseService,
        permission_resolver_service_1.PermissionResolverService])
], HiringSourcesService);
//# sourceMappingURL=hiring_sources.service.js.map