"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "PrinterMaintenanceLogService", {
    enumerable: true,
    get: function() {
        return PrinterMaintenanceLogService;
    }
});
const _printermaintenancelogentity = require("../../entities/printer-maintenance-log.entity");
const _runtimeexceptions = require("../../exceptions/runtime.exceptions");
class PrinterMaintenanceLogService {
    printerService;
    logger;
    repository;
    constructor(loggerFactory, typeormService, printerService){
        this.printerService = printerService;
        this.logger = loggerFactory(PrinterMaintenanceLogService.name);
        this.repository = typeormService.getDataSource().getRepository(_printermaintenancelogentity.PrinterMaintenanceLog);
    }
    toDto(entity) {
        return {
            id: entity.id,
            createdAt: entity.createdAt,
            createdBy: entity.createdBy,
            createdByUserId: entity.createdByUserId,
            printerId: entity.printerId,
            printerName: entity.printerName,
            printerUrl: entity.printerUrl,
            metadata: entity.metadata,
            completed: entity.completed,
            completedAt: entity.completedAt,
            completedByUserId: entity.completedByUserId,
            completedBy: entity.completedBy
        };
    }
    async create(dto, userId, username) {
        const printer = await this.printerService.get(dto.printerId);
        const existingLog = await this.repository.findOne({
            where: {
                printerId: dto.printerId,
                completed: false
            }
        });
        if (existingLog) {
            throw new _runtimeexceptions.BadRequestException(`Printer ${printer.name} already has an active maintenance log`);
        }
        const log = this.repository.create({
            printerId: dto.printerId,
            printerName: printer.name,
            printerUrl: printer.printerURL,
            metadata: dto.metadata,
            createdBy: username,
            createdByUserId: userId,
            completed: false
        });
        await this.repository.save(log);
        await this.printerService.updateDisabledReason(dto.printerId, this.buildDisabledReasonFromMetadata(dto.metadata));
        return log;
    }
    async complete(logId, dto, userId, username) {
        const log = await this.repository.findOne({
            where: {
                id: logId
            }
        });
        if (!log) {
            throw new _runtimeexceptions.NotFoundException(`Maintenance log with id ${logId} not found`);
        }
        if (log.completed) {
            throw new _runtimeexceptions.BadRequestException(`Maintenance log ${logId} is already completed`);
        }
        log.metadata = {
            ...log.metadata,
            completionNotes: dto.completionNotes
        };
        log.completed = true;
        log.completedAt = new Date();
        log.completedBy = username;
        log.completedByUserId = userId;
        await this.repository.save(log);
        if (log.printerId) {
            await this.printerService.updateDisabledReason(log.printerId, null);
        }
        return log;
    }
    async get(logId) {
        const log = await this.repository.findOne({
            where: {
                id: logId
            }
        });
        if (!log) {
            throw new _runtimeexceptions.NotFoundException(`Maintenance log with id ${logId} not found`);
        }
        return log;
    }
    async getActiveByPrinterId(printerId) {
        return this.repository.findOne({
            where: {
                printerId,
                completed: false
            }
        });
    }
    async list(filters) {
        const { printerId, completed, page = 1, pageSize = 20 } = filters;
        const queryBuilder = this.repository.createQueryBuilder("log");
        if (printerId !== undefined) {
            queryBuilder.andWhere("log.printerId = :printerId", {
                printerId
            });
        }
        if (completed !== undefined) {
            queryBuilder.andWhere("log.completed = :completed", {
                completed
            });
        }
        queryBuilder.orderBy("log.createdAt", "DESC");
        queryBuilder.skip((page - 1) * pageSize);
        queryBuilder.take(pageSize);
        const [logs, total] = await queryBuilder.getManyAndCount();
        return {
            logs,
            total
        };
    }
    async delete(logId) {
        const log = await this.get(logId);
        if (!log.completed && log.printerId) {
            await this.printerService.updateDisabledReason(log.printerId, null);
        }
        await this.repository.delete(logId);
    }
    buildDisabledReasonFromMetadata(metadata) {
        const parts = [];
        if (metadata.cause) {
            parts.push(metadata.cause);
        }
        if (metadata.partsInvolved && metadata.partsInvolved.length > 0) {
            parts.push(`Parts: ${metadata.partsInvolved.join(", ")}`);
        }
        if (metadata.notes) {
            parts.push(metadata.notes);
        }
        return parts.join(" - ") || "Under maintenance";
    }
}

//# sourceMappingURL=printer-maintenance-log.service.js.map