"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 UserSupportController_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.UserSupportController = void 0;
const common_1 = require("@nestjs/common");
const swagger_1 = require("@nestjs/swagger");
const support_service_1 = require("../../adminapi/support/support.service");
const CreateTicketWithMessageDto_1 = require("../../adminapi/support/CreateTicketWithMessageDto");
const create_comment_dto_1 = require("../../adminapi/support/create-comment.dto");
const user_services_1 = require("../user/user.services");
const firebase_service_1 = require("../fcm/firebase.service");
let UserSupportController = UserSupportController_1 = class UserSupportController {
    constructor(supportService, userService, firebaseService) {
        this.supportService = supportService;
        this.userService = userService;
        this.firebaseService = firebaseService;
        this.logger = new common_1.Logger(UserSupportController_1.name);
    }
    async create(dto) {
        try {
            const ticket = await this.supportService.createTicket(dto);
            const admins = await this.userService.findAdmin();
            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());
            for (const token of adminTokens) {
                try {
                    await this.firebaseService.sendNotification(token, 'New Support Ticket', `A user created a new support ticket: ${ticket?.id ?? 'N/A'}`, 'Support');
                }
                catch (err) {
                    this.logger.error(`Failed to notify admin token ${token}: ${err?.message}`);
                }
            }
            return { status: true, message: 'Ticket created successfully.', data: ticket };
        }
        catch (error) {
            throw new common_1.BadRequestException(error?.message ?? 'Unable to create ticket');
        }
    }
    async findByUser(userId, page, limit, status) {
        try {
            const [items, total] = await this.supportService.findAll({
                page: page ? Number(page) : undefined,
                limit: limit ? Number(limit) : undefined,
                status: status,
                vendorId: userId,
                order: 'ASC',
            });
            return { status: true, message: 'Ticket list.', data: { items, total } };
        }
        catch (error) {
            throw new common_1.BadRequestException(error?.message ?? 'Unable to fetch tickets');
        }
    }
    async findOne(id) {
        try {
            const ticket = await this.supportService.findOne(id);
            return { status: true, message: 'Ticket details.', data: ticket };
        }
        catch (error) {
            throw new common_1.BadRequestException(error?.message ?? 'Ticket not found');
        }
    }
    async addComment(id, dto) {
        try {
            const comment = await this.supportService.addComment(id, { ...dto, author: dto.author ?? 'user' });
            const admins = await this.userService.findAdmin();
            const clean = (t) => t && t !== 'null' && t !== 'undefined' ? String(t) : null;
            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 user added a comment to a support ticket.', 'Support');
                }
                catch (err) {
                    this.logger.error(`Failed to notify admin token ${token}: ${err?.message}`);
                }
            }
            return { status: true, message: 'Comment added.', data: comment };
        }
        catch (error) {
            throw new common_1.BadRequestException(error?.message ?? 'Unable to add comment');
        }
    }
};
exports.UserSupportController = UserSupportController;
__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)
], UserSupportController.prototype, "create", null);
__decorate([
    (0, common_1.Get)('user/:userId'),
    (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 }),
    __param(0, (0, common_1.Param)('userId')),
    __param(1, (0, common_1.Query)('page')),
    __param(2, (0, common_1.Query)('limit')),
    __param(3, (0, common_1.Query)('status')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String, String, String]),
    __metadata("design:returntype", Promise)
], UserSupportController.prototype, "findByUser", 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)
], UserSupportController.prototype, "findOne", 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)
], UserSupportController.prototype, "addComment", null);
exports.UserSupportController = UserSupportController = UserSupportController_1 = __decorate([
    (0, common_1.Controller)('app/tickets'),
    __metadata("design:paramtypes", [support_service_1.SupportService,
        user_services_1.UserService,
        firebase_service_1.FirebaseService])
], UserSupportController);
//# sourceMappingURL=user-support.controller.js.map