"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);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var SupportController_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SupportController = void 0;
const common_1 = require("@nestjs/common");
const support_service_1 = require("./support.service");
const update_ticket_dto_1 = require("./update-ticket.dto");
const update_status_dto_1 = require("./update-status.dto");
const create_comment_dto_1 = require("./create-comment.dto");
const CreateTicketWithMessageDto_1 = require("./CreateTicketWithMessageDto");
const swagger_1 = require("@nestjs/swagger");
const user_services_1 = require("../../appapi/user/user.services");
const firebase_service_1 = require("../../appapi/fcm/firebase.service");
const typeorm_1 = require("typeorm");
const ticket_entity_1 = require("./ticket.entity");
const typeorm_2 = require("@nestjs/typeorm");
let SupportController = SupportController_1 = class SupportController {
    constructor(service, userService, firebaseService, ticketRepo) {
        this.service = service;
        this.userService = userService;
        this.firebaseService = firebaseService;
        this.ticketRepo = ticketRepo;
        this.logger = new common_1.Logger(SupportController_1.name);
    }
    async create(dto) {
        try {
            const ticket = await this.service.createTicket(dto);
            const admins = await this.userService.findAdmin();
            this.logger.debug(`Admins found: ${admins?.length ?? 0}`);
            const adminTokens = (admins || [])
                .map(a => a?.deviceId)
                .filter(t => !!t && String(t).trim() !== '' && String(t).toLowerCase() !== 'null' && String(t).toLowerCase() !== 'undefined')
                .map(t => String(t).trim());
            if (adminTokens.length === 0) {
                this.logger.warn('No valid admin device tokens found. Skipping notifications.');
            }
            else {
                const title = 'New Support Ticket 🛎️';
                const body = `A vendor created a new support ticket: ${ticket?.id ?? 'N/A'}`;
                this.logger.log(`Sending notification to ${adminTokens.length} admin device(s).`);
                for (const token of adminTokens) {
                    try {
                        await this.firebaseService.sendNotification(token, title, body, 'Support');
                        this.logger.log(`Notification sent to admin token: ${token}`);
                    }
                    catch (err) {
                        this.logger.error(`Failed to send notification to ${token}: ${err?.message ?? err}`, err?.stack);
                    }
                }
            }
            return {
                status: true,
                message: 'Ticket created successfully.',
                data: ticket,
            };
        }
        catch (error) {
            this.logger.error('Error creating ticket', error?.stack ?? error);
            throw new common_1.BadRequestException(error?.message ?? 'Unable to create ticket');
        }
    }
    async findAll(page, limit, status, priority, q, vendorId, userId) {
        const pageNum = page ? Number(page) : undefined;
        const limitNum = limit ? Number(limit) : undefined;
        const [items, total] = await this.service.findAll({
            page: pageNum,
            limit: limitNum,
            status: status,
            priority: priority,
            q,
            vendorId: userId ?? vendorId,
        });
        if (pageNum && limitNum) {
            return { items, total, page: pageNum, limit: limitNum };
        }
        return { items, total };
    }
    async findOne(id) {
        return this.service.findOne(id);
    }
    async update(id, dto) {
        return this.service.updateTicket(id, dto);
    }
    async updateStatus(id, body) {
        return this.service.updateStatus(id, body.status);
    }
    async addComment(id, dto) {
        const comment = await this.service.addComment(id, dto);
        const ticket = await this.ticketRepo.findOne({ where: { id } });
        const user = await this.userService.findById(Number(ticket.userId));
        const clean = (t) => t && t !== 'null' && t !== 'undefined' ? String(t) : null;
        const userToken = clean(user?.deviceId);
        if (dto.author === 'admin') {
            if (userToken) {
                try {
                    await this.firebaseService.sendNotification(userToken, 'New Comment on Your Ticket 📝', 'A new comment was added to your ticket.', 'Support');
                }
                catch (err) {
                    this.logger.error(`Failed to send support notification to user token ${userToken}: ${err?.message ?? err}`, err?.stack);
                }
            }
        }
        else {
            const admins = await this.userService.findAdmin();
            this.logger.log(`Sending notification to ${admins}`);
            const adminTokens = admins
                .map(a => clean(a.deviceId))
                .filter(Boolean);
            for (const token of adminTokens) {
                try {
                    await this.firebaseService.sendNotification(token, 'New Ticket Comment 🛎️', 'A new comment was added to a ticket.', 'Support');
                }
                catch (err) {
                    this.logger.error(`Failed to send support notification to admin token ${token}: ${err?.message ?? err}`, err?.stack);
                }
            }
        }
        return comment;
    }
    async remove(id) {
        return this.service.remove(id);
    }
};
exports.SupportController = SupportController;
__decorate([
    (0, common_1.Post)(),
    __param(0, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [CreateTicketWithMessageDto_1.CreateTicketWithMessageDto]),
    __metadata("design:returntype", Promise)
], SupportController.prototype, "create", null);
__decorate([
    (0, common_1.Get)(),
    (0, swagger_1.ApiQuery)({ name: 'page', required: false, type: Number }),
    (0, swagger_1.ApiQuery)({ name: 'limit', required: false, type: Number }),
    (0, swagger_1.ApiQuery)({ name: 'status', required: false, type: String }),
    (0, swagger_1.ApiQuery)({ name: 'priority', required: false, type: String }),
    (0, swagger_1.ApiQuery)({ name: 'q', required: false, type: String }),
    (0, swagger_1.ApiQuery)({ name: 'vendorId', required: false, type: String }),
    (0, swagger_1.ApiQuery)({ name: 'userId', required: false, type: String }),
    __param(0, (0, common_1.Query)('page')),
    __param(1, (0, common_1.Query)('limit')),
    __param(2, (0, common_1.Query)('status')),
    __param(3, (0, common_1.Query)('priority')),
    __param(4, (0, common_1.Query)('q')),
    __param(5, (0, common_1.Query)('vendorId')),
    __param(6, (0, common_1.Query)('userId')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String, String, String, String, String, String]),
    __metadata("design:returntype", Promise)
], SupportController.prototype, "findAll", null);
__decorate([
    (0, common_1.Get)(':id'),
    __param(0, (0, common_1.Param)('id', common_1.ParseUUIDPipe)),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], SupportController.prototype, "findOne", null);
__decorate([
    (0, common_1.Patch)(':id'),
    __param(0, (0, common_1.Param)('id', common_1.ParseUUIDPipe)),
    __param(1, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, update_ticket_dto_1.UpdateTicketDto]),
    __metadata("design:returntype", Promise)
], SupportController.prototype, "update", null);
__decorate([
    (0, common_1.Patch)(':id/status'),
    __param(0, (0, common_1.Param)('id', common_1.ParseUUIDPipe)),
    __param(1, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, update_status_dto_1.UpdateStatusDto]),
    __metadata("design:returntype", Promise)
], SupportController.prototype, "updateStatus", null);
__decorate([
    (0, common_1.Post)(':id/comments'),
    __param(0, (0, common_1.Param)('id', common_1.ParseUUIDPipe)),
    __param(1, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, create_comment_dto_1.CreateCommentDto]),
    __metadata("design:returntype", Promise)
], SupportController.prototype, "addComment", null);
__decorate([
    (0, common_1.Delete)(':id'),
    (0, common_1.HttpCode)(200),
    __param(0, (0, common_1.Param)('id', common_1.ParseUUIDPipe)),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], SupportController.prototype, "remove", null);
exports.SupportController = SupportController = SupportController_1 = __decorate([
    (0, common_1.Controller)('tickets'),
    __param(3, (0, typeorm_2.InjectRepository)(ticket_entity_1.Ticket)),
    __metadata("design:paramtypes", [support_service_1.SupportService,
        user_services_1.UserService,
        firebase_service_1.FirebaseService,
        typeorm_1.Repository])
], SupportController);
//# sourceMappingURL=support.controller.js.map