"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); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AdminDocumentController = void 0;
const common_1 = require("@nestjs/common");
const document_service_1 = require("./document.service");
const JwtAuthGuard_1 = require("../../guards/JwtAuthGuard");
const roles_guard_1 = require("../../appapi/user/auth/roles.guard");
const swagger_1 = require("@nestjs/swagger");
const firebase_service_1 = require("../../appapi/fcm/firebase.service");
const user_services_1 = require("../../appapi/user/user.services");
let AdminDocumentController = class AdminDocumentController {
    constructor(adminDocumentService, firebaseService, userService) {
        this.adminDocumentService = adminDocumentService;
        this.firebaseService = firebaseService;
        this.userService = userService;
    }
    async create(createDocumentDto, req) {
        const dtosWithVendorId = (createDocumentDto.documents || []).map(d => ({
            ...d,
            vendorId: req.user.userId,
        }));
        const catDtosWithVendorId = {
            categories: createDocumentDto.categories || [],
            vendorId: req.user.userId,
        };
        await this.adminDocumentService.create(dtosWithVendorId, catDtosWithVendorId);
        const admins = await this.userService.findAdmin();
        const clean = (t) => t && String(t).trim() !== '' && String(t).toLowerCase() !== 'null' && String(t).toLowerCase() !== 'undefined'
            ? String(t).trim()
            : null;
        const adminTokens = (admins || [])
            .map(a => clean(a.deviceId))
            .filter(Boolean);
        for (const token of adminTokens) {
            try {
                await this.firebaseService.sendNotification(token, 'New Documents Uploaded 📄', `A vendor uploaded ${dtosWithVendorId.length} document(s).`, 'Documents');
            }
            catch (fcmError) {
                console.error(`FCM notification failed for admin token ${token}:`, fcmError?.message ?? fcmError);
            }
        }
        return {
            status: true,
            message: 'Document Successfully created.',
        };
    }
    async findAll(req, query) {
        try {
            let documents;
            if (req.user.roles.includes('vendor')) {
                documents = await this.adminDocumentService.findByVendorId(req.user.userId);
            }
            else if (req.user.roles.includes('admin') || req.user.roles.includes('super_admin')) {
                const vendorId = query.vendorId;
                if (vendorId) {
                    documents = await this.adminDocumentService.findByVendorId(vendorId);
                }
                else {
                    documents = await this.adminDocumentService.findAll();
                }
            }
            else {
                throw new common_1.BadRequestException("Unauthorized access");
            }
            return {
                status: true,
                message: "Document list.",
                data: documents,
            };
        }
        catch (error) {
            throw new common_1.BadRequestException(error.message);
        }
    }
    async findOne(id) {
        try {
            const document = await this.adminDocumentService.findOne(+id);
            return {
                status: true,
                message: "Document detail.",
                data: document,
            };
        }
        catch (error) {
            throw new common_1.BadRequestException(error.message);
        }
    }
    async update(id, UpdateDocumentDto, req) {
        try {
            const dtosWithVendorId = UpdateDocumentDto['documents'].map(dto => ({
                ...dto,
                vendorId: req.user.userId,
            }));
            const catDtosWithVendorId = { categories: UpdateDocumentDto['categories'], vendorId: req.user.userId };
            const res = await this.adminDocumentService.updateMultiple(dtosWithVendorId, catDtosWithVendorId);
            return {
                status: true,
                message: "Document Successfully updated.",
            };
        }
        catch (error) {
            throw new common_1.BadRequestException(error.message);
        }
    }
    async remove(id) {
        try {
            const res = await this.adminDocumentService.remove(+id);
            return {
                status: true,
                message: "Document Successfully deleted.",
            };
        }
        catch (error) {
            throw new common_1.BadRequestException(error.message);
        }
    }
};
exports.AdminDocumentController = AdminDocumentController;
__decorate([
    (0, common_1.Post)(),
    __param(0, (0, common_1.Body)()),
    __param(1, (0, common_1.Req)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object]),
    __metadata("design:returntype", Promise)
], AdminDocumentController.prototype, "create", null);
__decorate([
    (0, common_1.Get)(),
    (0, swagger_1.ApiQuery)({ name: 'vendorId', required: false, type: String }),
    __param(0, (0, common_1.Req)()),
    __param(1, (0, common_1.Query)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object]),
    __metadata("design:returntype", Promise)
], AdminDocumentController.prototype, "findAll", null);
__decorate([
    (0, common_1.Get)(":id"),
    __param(0, (0, common_1.Param)("id")),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], AdminDocumentController.prototype, "findOne", null);
__decorate([
    (0, common_1.Patch)(":id"),
    __param(0, (0, common_1.Param)("id")),
    __param(1, (0, common_1.Body)()),
    __param(2, (0, common_1.Req)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Array, Object]),
    __metadata("design:returntype", Promise)
], AdminDocumentController.prototype, "update", null);
__decorate([
    (0, common_1.Delete)(":id"),
    __param(0, (0, common_1.Param)("id")),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], AdminDocumentController.prototype, "remove", null);
exports.AdminDocumentController = AdminDocumentController = __decorate([
    (0, common_1.UseGuards)(JwtAuthGuard_1.JwtAuthGuard, roles_guard_1.RolesGuard),
    (0, common_1.Controller)("admin/document"),
    __metadata("design:paramtypes", [document_service_1.AdminDocumentService,
        firebase_service_1.FirebaseService,
        user_services_1.UserService])
], AdminDocumentController);
//# sourceMappingURL=document.controller.js.map