"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
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 __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
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.NotificationsController = void 0;
const common_1 = require("@nestjs/common");
const notifications_service_1 = require("./notifications.service");
const jwt_auth_guard_1 = require("../common/guards/jwt-auth.guard");
const roles_guard_1 = require("../common/guards/roles.guard");
const roles_decorator_1 = require("../common/decorators/roles.decorator");
const role_enum_1 = require("../common/roles/role.enum");
const current_user_decorator_1 = require("../common/decorators/current-user.decorator");
const create_notification_dto_1 = require("./dto/create-notification.dto");
const update_notification_dto_1 = require("./dto/update-notification.dto");
const platform_express_1 = require("@nestjs/platform-express");
const multer_1 = require("multer");
const path_1 = require("path");
const fs = __importStar(require("fs"));
const mongo_id_pipe_1 = require("../common/pipes/mongo-id.pipe");
const url_helper_1 = require("../common/helpers/url.helper");
const ensureDir = (dir) => {
    if (!fs.existsSync(dir))
        fs.mkdirSync(dir, { recursive: true });
};
const storage = (0, multer_1.diskStorage)({
    destination: (_req, _file, cb) => {
        const dir = (0, path_1.join)(process.cwd(), 'uploads', 'notifications');
        ensureDir(dir);
        cb(null, dir);
    },
    filename: (_req, file, cb) => {
        const name = Date.now() + '-' + Math.random().toString(36).slice(2);
        cb(null, name + (0, path_1.extname)(file.originalname));
    },
});
const fileFilter = (_req, file, cb) => {
    const ok = /\.(pdf|doc|docx|xls|xlsx|ppt|pptx|jpg|jpeg|png)$/i.test(file.originalname);
    if (!ok)
        return cb(new Error('Only PDF/DOC/XLS/PPT or JPG/PNG files allowed'), false);
    cb(null, true);
};
let NotificationsController = class NotificationsController {
    notificationsService;
    constructor(notificationsService) {
        this.notificationsService = notificationsService;
    }
    async send(dto, id, currentAyId, file) {
        if (!id)
            throw new common_1.UnauthorizedException('Missing user id');
        if (currentAyId) {
            dto.academicYearId = currentAyId;
        }
        let fileMeta;
        if (file && file.filename) {
            fileMeta = {
                fileUrl: (0, url_helper_1.toFullUrl)(`/uploads/notifications/${file.filename}`),
                fileName: file.originalname,
                fileType: file.mimetype,
                fileSize: file.size,
            };
        }
        else if (dto.fileUrl) {
            fileMeta = {
                fileUrl: dto.fileUrl,
                fileName: dto.fileName,
                fileType: dto.fileType,
                fileSize: dto.fileSize,
            };
        }
        return this.notificationsService.sendNotification(dto, id, fileMeta);
    }
    async myFeed(id, role, limit, ayHeader) {
        const n = Number(limit) || 5;
        if (role === role_enum_1.Role.STUDENT) {
            return this.notificationsService.getForStudent(id, n, ayHeader);
        }
        if (role === role_enum_1.Role.TEACHER) {
            return this.notificationsService.getForTeacher(id, n, ayHeader);
        }
        return this.notificationsService.getRecent(n);
    }
    async getUnreadCount(id, role, ayHeader) {
        return this.notificationsService.getUnreadCount(id, role, ayHeader);
    }
    async markAllAsRead(id, role, ayHeader) {
        return this.notificationsService.markAllAsRead(id, role, ayHeader);
    }
    async dismissAll(id, role, ayHeader) {
        return this.notificationsService.dismissAll(id, role, ayHeader);
    }
    findAll() {
        return this.notificationsService.findAll();
    }
    filter(type, status, sentBy, academicYearId, classId, sectionId, q, hasFile, ayHeader) {
        return this.notificationsService.filter({
            type,
            status,
            sentBy,
            academicYearId: academicYearId ?? ayHeader,
            classId,
            sectionId,
            q,
            hasFile,
        });
    }
    getRecent(limit, ayHeader) {
        return this.notificationsService.getRecent(Number(limit) || 5, ayHeader);
    }
    getRecipients(id) {
        return this.notificationsService.getRecipients(id);
    }
    async getFile(id, userId, role, ayHeader) {
        const hasAccess = await this.notificationsService.canUserAccessNotification(id, userId, role, ayHeader);
        if (!hasAccess) {
            throw new common_1.UnauthorizedException('You do not have access to this notification');
        }
        const n = await this.notificationsService.findOne(id);
        if (!n?.fileUrl)
            return { hasFile: false };
        return {
            hasFile: true,
            fileUrl: n.fileUrl,
            fileName: n.fileName,
            fileType: n.fileType,
            fileSize: n.fileSize,
        };
    }
    findOne(id) {
        return this.notificationsService.findOne(id);
    }
    async markAsRead(id, userId, role, ayHeader) {
        const hasAccess = await this.notificationsService.canUserAccessNotification(id, userId, role, ayHeader);
        if (!hasAccess) {
            throw new common_1.UnauthorizedException('You do not have access to this notification');
        }
        return this.notificationsService.markAsRead(id, userId);
    }
    async dismiss(id, userId, role, ayHeader) {
        const hasAccess = await this.notificationsService.canUserAccessNotification(id, userId, role, ayHeader);
        if (!hasAccess) {
            throw new common_1.UnauthorizedException('You do not have access to this notification');
        }
        return this.notificationsService.dismiss(id, userId);
    }
    async update(id, dto, currentAyId, file) {
        if (currentAyId) {
            dto.academicYearId = currentAyId;
        }
        let fileMeta;
        if (file && file.filename) {
            fileMeta = {
                fileUrl: (0, url_helper_1.toFullUrl)(`/uploads/notifications/${file.filename}`),
                fileName: file.originalname,
                fileType: file.mimetype,
                fileSize: file.size,
            };
        }
        else if (dto.fileUrl) {
            fileMeta = {
                fileUrl: dto.fileUrl,
                fileName: dto.fileName,
                fileType: dto.fileType,
                fileSize: dto.fileSize,
            };
        }
        return this.notificationsService.update(id, dto, fileMeta);
    }
    remove(id) {
        return this.notificationsService.delete(id);
    }
};
exports.NotificationsController = NotificationsController;
__decorate([
    (0, common_1.Post)(),
    (0, roles_decorator_1.Roles)(role_enum_1.Role.ADMIN),
    (0, common_1.UseInterceptors)((0, platform_express_1.FileInterceptor)('file', {
        storage,
        fileFilter,
        limits: { fileSize: 10 * 1024 * 1024 },
    })),
    __param(0, (0, common_1.Body)()),
    __param(1, (0, current_user_decorator_1.CurrentUser)('id')),
    __param(2, (0, common_1.Headers)('x-academic-year-id')),
    __param(3, (0, common_1.UploadedFile)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [create_notification_dto_1.CreateNotificationDto, String, String, Object]),
    __metadata("design:returntype", Promise)
], NotificationsController.prototype, "send", null);
__decorate([
    (0, common_1.Get)('me'),
    (0, roles_decorator_1.Roles)(role_enum_1.Role.ADMIN, role_enum_1.Role.TEACHER, role_enum_1.Role.STUDENT),
    __param(0, (0, current_user_decorator_1.CurrentUser)('id')),
    __param(1, (0, current_user_decorator_1.CurrentUser)('role')),
    __param(2, (0, common_1.Query)('limit')),
    __param(3, (0, common_1.Headers)('x-academic-year-id')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String, String, String]),
    __metadata("design:returntype", Promise)
], NotificationsController.prototype, "myFeed", null);
__decorate([
    (0, common_1.Get)('unread-count'),
    (0, roles_decorator_1.Roles)(role_enum_1.Role.ADMIN, role_enum_1.Role.TEACHER, role_enum_1.Role.STUDENT),
    __param(0, (0, current_user_decorator_1.CurrentUser)('id')),
    __param(1, (0, current_user_decorator_1.CurrentUser)('role')),
    __param(2, (0, common_1.Headers)('x-academic-year-id')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String, String]),
    __metadata("design:returntype", Promise)
], NotificationsController.prototype, "getUnreadCount", null);
__decorate([
    (0, common_1.Post)('mark-all-read'),
    (0, roles_decorator_1.Roles)(role_enum_1.Role.TEACHER, role_enum_1.Role.STUDENT),
    __param(0, (0, current_user_decorator_1.CurrentUser)('id')),
    __param(1, (0, current_user_decorator_1.CurrentUser)('role')),
    __param(2, (0, common_1.Headers)('x-academic-year-id')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String, String]),
    __metadata("design:returntype", Promise)
], NotificationsController.prototype, "markAllAsRead", null);
__decorate([
    (0, common_1.Post)('dismiss-all'),
    (0, roles_decorator_1.Roles)(role_enum_1.Role.TEACHER, role_enum_1.Role.STUDENT),
    __param(0, (0, current_user_decorator_1.CurrentUser)('id')),
    __param(1, (0, current_user_decorator_1.CurrentUser)('role')),
    __param(2, (0, common_1.Headers)('x-academic-year-id')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String, String]),
    __metadata("design:returntype", Promise)
], NotificationsController.prototype, "dismissAll", null);
__decorate([
    (0, common_1.Get)(),
    (0, roles_decorator_1.Roles)(role_enum_1.Role.ADMIN),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", void 0)
], NotificationsController.prototype, "findAll", null);
__decorate([
    (0, common_1.Get)('filter'),
    (0, roles_decorator_1.Roles)(role_enum_1.Role.ADMIN),
    __param(0, (0, common_1.Query)('type')),
    __param(1, (0, common_1.Query)('status')),
    __param(2, (0, common_1.Query)('sentBy')),
    __param(3, (0, common_1.Query)('academicYearId')),
    __param(4, (0, common_1.Query)('classId')),
    __param(5, (0, common_1.Query)('sectionId')),
    __param(6, (0, common_1.Query)('q')),
    __param(7, (0, common_1.Query)('hasFile')),
    __param(8, (0, common_1.Headers)('x-academic-year-id')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String, String, String, String, String, String, String, String]),
    __metadata("design:returntype", void 0)
], NotificationsController.prototype, "filter", null);
__decorate([
    (0, common_1.Get)('recent'),
    (0, roles_decorator_1.Roles)(role_enum_1.Role.ADMIN),
    __param(0, (0, common_1.Query)('limit')),
    __param(1, (0, common_1.Headers)('x-academic-year-id')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String]),
    __metadata("design:returntype", void 0)
], NotificationsController.prototype, "getRecent", null);
__decorate([
    (0, common_1.Get)(':id/recipients'),
    (0, roles_decorator_1.Roles)(role_enum_1.Role.ADMIN),
    __param(0, (0, common_1.Param)('id', new mongo_id_pipe_1.MongoIdPipe())),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", void 0)
], NotificationsController.prototype, "getRecipients", null);
__decorate([
    (0, common_1.Get)(':id/file'),
    (0, roles_decorator_1.Roles)(role_enum_1.Role.ADMIN, role_enum_1.Role.TEACHER, role_enum_1.Role.STUDENT),
    __param(0, (0, common_1.Param)('id', new mongo_id_pipe_1.MongoIdPipe())),
    __param(1, (0, current_user_decorator_1.CurrentUser)('id')),
    __param(2, (0, current_user_decorator_1.CurrentUser)('role')),
    __param(3, (0, common_1.Headers)('x-academic-year-id')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String, String, String]),
    __metadata("design:returntype", Promise)
], NotificationsController.prototype, "getFile", null);
__decorate([
    (0, common_1.Get)(':id'),
    (0, roles_decorator_1.Roles)(role_enum_1.Role.ADMIN),
    __param(0, (0, common_1.Param)('id', new mongo_id_pipe_1.MongoIdPipe())),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", void 0)
], NotificationsController.prototype, "findOne", null);
__decorate([
    (0, common_1.Post)(':id/read'),
    (0, roles_decorator_1.Roles)(role_enum_1.Role.TEACHER, role_enum_1.Role.STUDENT),
    __param(0, (0, common_1.Param)('id', new mongo_id_pipe_1.MongoIdPipe())),
    __param(1, (0, current_user_decorator_1.CurrentUser)('id')),
    __param(2, (0, current_user_decorator_1.CurrentUser)('role')),
    __param(3, (0, common_1.Headers)('x-academic-year-id')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String, String, String]),
    __metadata("design:returntype", Promise)
], NotificationsController.prototype, "markAsRead", null);
__decorate([
    (0, common_1.Post)(':id/dismiss'),
    (0, roles_decorator_1.Roles)(role_enum_1.Role.TEACHER, role_enum_1.Role.STUDENT),
    __param(0, (0, common_1.Param)('id', new mongo_id_pipe_1.MongoIdPipe())),
    __param(1, (0, current_user_decorator_1.CurrentUser)('id')),
    __param(2, (0, current_user_decorator_1.CurrentUser)('role')),
    __param(3, (0, common_1.Headers)('x-academic-year-id')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String, String, String]),
    __metadata("design:returntype", Promise)
], NotificationsController.prototype, "dismiss", null);
__decorate([
    (0, common_1.Put)(':id'),
    (0, roles_decorator_1.Roles)(role_enum_1.Role.ADMIN),
    (0, common_1.UseInterceptors)((0, platform_express_1.FileInterceptor)('file', {
        storage,
        fileFilter,
        limits: { fileSize: 10 * 1024 * 1024 },
    })),
    __param(0, (0, common_1.Param)('id', new mongo_id_pipe_1.MongoIdPipe())),
    __param(1, (0, common_1.Body)()),
    __param(2, (0, common_1.Headers)('x-academic-year-id')),
    __param(3, (0, common_1.UploadedFile)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, update_notification_dto_1.UpdateNotificationDto, String, Object]),
    __metadata("design:returntype", Promise)
], NotificationsController.prototype, "update", null);
__decorate([
    (0, common_1.Delete)(':id'),
    (0, roles_decorator_1.Roles)(role_enum_1.Role.ADMIN),
    __param(0, (0, common_1.Param)('id', new mongo_id_pipe_1.MongoIdPipe())),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", void 0)
], NotificationsController.prototype, "remove", null);
exports.NotificationsController = NotificationsController = __decorate([
    (0, common_1.UseGuards)(jwt_auth_guard_1.JwtAuthGuard, roles_guard_1.RolesGuard),
    (0, common_1.Controller)('notifications'),
    __metadata("design:paramtypes", [notifications_service_1.NotificationsService])
], NotificationsController);
//# sourceMappingURL=notifications.controller.js.map