"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.SettingsService = void 0;
const common_1 = require("@nestjs/common");
const mongoose_1 = require("@nestjs/mongoose");
const mongoose_2 = require("mongoose");
const settings_schema_1 = require("./schemas/settings.schema");
const fs = __importStar(require("fs/promises"));
const path = __importStar(require("path"));
const crypto_1 = require("crypto");
const url_helper_1 = require("../common/helpers/url.helper");
let SettingsService = class SettingsService {
    settingsModel;
    constructor(settingsModel) {
        this.settingsModel = settingsModel;
    }
    DEFAULTS = {
        schoolName: 'School Management System',
        theme: 'light',
        primaryColor: '#4c3cc9',
        secondaryColor: '#3f2fb1',
        showWhatsapp: false,
        sidebarCollapsed: false,
    };
    async getSettings() {
        const settings = await this.settingsModel
            .findOneAndUpdate({ _singleton: 'singleton' }, {
            $setOnInsert: {
                _singleton: 'singleton',
                ...this.DEFAULTS,
            },
        }, { new: true, upsert: true, runValidators: true })
            .lean();
        return {
            ...settings,
            schoolName: settings.schoolName || 'School Management System',
            theme: settings.theme || 'light',
            primaryColor: settings.primaryColor || '#4c3cc9',
            secondaryColor: settings.secondaryColor || '#3f2fb1',
            showWhatsapp: settings.showWhatsapp ?? false,
            sidebarCollapsed: settings.sidebarCollapsed ?? false,
            logoUrl: settings.logoUrl ? (0, url_helper_1.toFullUrl)(settings.logoUrl) : settings.logoUrl,
            loginLogoUrl: settings.loginLogoUrl ? (0, url_helper_1.toFullUrl)(settings.loginLogoUrl) : settings.loginLogoUrl,
            loginIllustrationUrl: settings.loginIllustrationUrl ? (0, url_helper_1.toFullUrl)(settings.loginIllustrationUrl) : settings.loginIllustrationUrl,
            faviconUrl: settings.faviconUrl ? (0, url_helper_1.toFullUrl)(settings.faviconUrl) : settings.faviconUrl,
            letterheadUrl: settings.letterheadUrl ? (0, url_helper_1.toFullUrl)(settings.letterheadUrl) : settings.letterheadUrl,
            authorizedSignatureUrl: settings.authorizedSignatureUrl ? (0, url_helper_1.toFullUrl)(settings.authorizedSignatureUrl) : settings.authorizedSignatureUrl,
        };
    }
    async getPublicSettings() {
        const s = await this.getSettings();
        return {
            schoolName: s.schoolName,
            logoUrl: s.logoUrl,
            loginLogoUrl: s.loginLogoUrl,
            loginIllustrationUrl: s.loginIllustrationUrl,
            faviconUrl: s.faviconUrl,
            loginMainHeading: s.loginMainHeading,
            loginWelcomeText: s.loginWelcomeText,
            loginPortalName: s.loginPortalName,
            loginTagline: s.loginTagline,
            loginIllustrationAlt: s.loginIllustrationAlt,
            theme: s.theme,
            primaryColor: s.primaryColor,
            secondaryColor: s.secondaryColor,
            primaryTextColor: s.primaryTextColor,
            secondaryTextColor: s.secondaryTextColor,
            lightPrimaryColor: s.lightPrimaryColor,
            lightSecondaryColor: s.lightSecondaryColor,
            lightPrimaryTextColor: s.lightPrimaryTextColor,
            lightSecondaryTextColor: s.lightSecondaryTextColor,
            darkPrimaryColor: s.darkPrimaryColor,
            darkSecondaryColor: s.darkSecondaryColor,
            darkPrimaryTextColor: s.darkPrimaryTextColor,
            darkSecondaryTextColor: s.darkSecondaryTextColor,
            showWhatsapp: s.showWhatsapp,
            whatsappNumber: s.showWhatsapp ? s.whatsappNumber : undefined,
            letterheadUrl: s.letterheadUrl,
            schoolAddress: s.schoolAddress,
            schoolPhone: s.schoolPhone,
            schoolEmail: s.schoolEmail,
            invoiceTerms: s.invoiceTerms,
            authorizedSignatureUrl: s.authorizedSignatureUrl,
        };
    }
    async updateSettings(dto) {
        const setFields = {};
        const unsetFields = {};
        for (const [key, value] of Object.entries(dto)) {
            if (value === null || value === undefined) {
                unsetFields[key] = 1;
            }
            else {
                setFields[key] = value;
            }
        }
        const updateOp = {};
        if (Object.keys(setFields).length > 0)
            updateOp.$set = setFields;
        if (Object.keys(unsetFields).length > 0)
            updateOp.$unset = unsetFields;
        if (Object.keys(updateOp).length === 0) {
            return this.getSettings();
        }
        const updated = await this.settingsModel
            .findOneAndUpdate({ _singleton: 'singleton' }, updateOp, { new: true, upsert: true, runValidators: true })
            .lean();
        if (!updated) {
            throw new common_1.NotFoundException('Failed to update settings');
        }
        return this.getSettings();
    }
    async uploadLogo(file) {
        if (!file)
            throw new common_1.NotFoundException('No file uploaded');
        const uploadsDir = path.join(process.cwd(), 'uploads', 'settings');
        await fs.mkdir(uploadsDir, { recursive: true });
        const filename = `logo-${(0, crypto_1.randomBytes)(16).toString('hex')}${path.extname(file.originalname)}`;
        const filepath = path.join(uploadsDir, filename);
        await fs.writeFile(filepath, file.buffer);
        const relativePath = `/uploads/settings/${filename}`;
        const existingSettings = await this.settingsModel.findOne({ _singleton: 'singleton' }).lean();
        if (existingSettings?.logoUrl) {
            let oldRelativePath;
            try {
                const urlObj = new URL(existingSettings.logoUrl);
                oldRelativePath = urlObj.pathname.replace('/schoolcrmbackend', '');
            }
            catch {
                oldRelativePath = existingSettings.logoUrl;
            }
            const oldPath = path.join(process.cwd(), oldRelativePath.replace(/^\//, ''));
            await fs.unlink(oldPath).catch(() => { });
        }
        const updated = await this.settingsModel
            .findOneAndUpdate({ _singleton: 'singleton' }, { $set: { logoUrl: relativePath } }, { new: true, upsert: true })
            .lean();
        if (!updated) {
            throw new common_1.NotFoundException('Failed to update logo');
        }
        const fullUrl = (0, url_helper_1.toFullUrl)(relativePath);
        return { logoUrl: fullUrl };
    }
    async deleteLogo() {
        const settings = await this.getSettings();
        if (settings.logoUrl) {
            let relativePath;
            try {
                const urlObj = new URL(settings.logoUrl);
                relativePath = urlObj.pathname.replace('/schoolcrmbackend', '');
            }
            catch {
                relativePath = settings.logoUrl;
            }
            const filepath = path.join(process.cwd(), relativePath.replace(/^\//, ''));
            await fs.unlink(filepath).catch(() => { });
        }
        await this.settingsModel.findOneAndUpdate({ _singleton: 'singleton' }, { $unset: { logoUrl: 1 } }, { new: true, upsert: true });
        return { message: 'Logo deleted successfully' };
    }
    async uploadLoginLogo(file) {
        if (!file)
            throw new common_1.NotFoundException('No file uploaded');
        const uploadsDir = path.join(process.cwd(), 'uploads', 'settings');
        await fs.mkdir(uploadsDir, { recursive: true });
        const filename = `login-logo-${(0, crypto_1.randomBytes)(16).toString('hex')}${path.extname(file.originalname)}`;
        const filepath = path.join(uploadsDir, filename);
        await fs.writeFile(filepath, file.buffer);
        const relativePath = `/uploads/settings/${filename}`;
        const existingSettings = await this.settingsModel.findOne({ _singleton: 'singleton' }).lean();
        if (existingSettings?.loginLogoUrl) {
            let oldRelativePath;
            try {
                const urlObj = new URL(existingSettings.loginLogoUrl);
                oldRelativePath = urlObj.pathname.replace('/schoolcrmbackend', '');
            }
            catch {
                oldRelativePath = existingSettings.loginLogoUrl;
            }
            const oldPath = path.join(process.cwd(), oldRelativePath.replace(/^\//, ''));
            await fs.unlink(oldPath).catch(() => { });
        }
        const updated = await this.settingsModel
            .findOneAndUpdate({ _singleton: 'singleton' }, { $set: { loginLogoUrl: relativePath } }, { new: true, upsert: true })
            .lean();
        if (!updated) {
            throw new common_1.NotFoundException('Failed to update login logo');
        }
        const fullUrl = (0, url_helper_1.toFullUrl)(relativePath);
        return { loginLogoUrl: fullUrl };
    }
    async deleteLoginLogo() {
        const settings = await this.getSettings();
        if (settings.loginLogoUrl) {
            let relativePath;
            try {
                const urlObj = new URL(settings.loginLogoUrl);
                relativePath = urlObj.pathname.replace('/schoolcrmbackend', '');
            }
            catch {
                relativePath = settings.loginLogoUrl;
            }
            const filepath = path.join(process.cwd(), relativePath.replace(/^\//, ''));
            await fs.unlink(filepath).catch(() => { });
        }
        await this.settingsModel.findOneAndUpdate({ _singleton: 'singleton' }, { $unset: { loginLogoUrl: 1 } }, { new: true, upsert: true });
        return { message: 'Login logo deleted successfully' };
    }
    async uploadLoginIllustration(file) {
        if (!file)
            throw new common_1.NotFoundException('No file uploaded');
        const uploadsDir = path.join(process.cwd(), 'uploads', 'settings');
        await fs.mkdir(uploadsDir, { recursive: true });
        const filename = `login-illustration-${(0, crypto_1.randomBytes)(16).toString('hex')}${path.extname(file.originalname)}`;
        const filepath = path.join(uploadsDir, filename);
        await fs.writeFile(filepath, file.buffer);
        const relativePath = `/uploads/settings/${filename}`;
        const existingSettings = await this.settingsModel.findOne({ _singleton: 'singleton' }).lean();
        if (existingSettings?.loginIllustrationUrl) {
            let oldRelativePath;
            try {
                const urlObj = new URL(existingSettings.loginIllustrationUrl);
                oldRelativePath = urlObj.pathname.replace('/schoolcrmbackend', '');
            }
            catch {
                oldRelativePath = existingSettings.loginIllustrationUrl;
            }
            const oldPath = path.join(process.cwd(), oldRelativePath.replace(/^\//, ''));
            await fs.unlink(oldPath).catch(() => { });
        }
        const updated = await this.settingsModel
            .findOneAndUpdate({ _singleton: 'singleton' }, { $set: { loginIllustrationUrl: relativePath } }, { new: true, upsert: true })
            .lean();
        if (!updated) {
            throw new common_1.NotFoundException('Failed to update login illustration');
        }
        const fullUrl = (0, url_helper_1.toFullUrl)(relativePath);
        return { loginIllustrationUrl: fullUrl };
    }
    async deleteLoginIllustration() {
        const settings = await this.getSettings();
        if (settings.loginIllustrationUrl) {
            let relativePath;
            try {
                const urlObj = new URL(settings.loginIllustrationUrl);
                relativePath = urlObj.pathname.replace('/schoolcrmbackend', '');
            }
            catch {
                relativePath = settings.loginIllustrationUrl;
            }
            const filepath = path.join(process.cwd(), relativePath.replace(/^\//, ''));
            await fs.unlink(filepath).catch(() => { });
        }
        await this.settingsModel.findOneAndUpdate({ _singleton: 'singleton' }, { $unset: { loginIllustrationUrl: 1 } }, { new: true, upsert: true });
        return { message: 'Login illustration deleted successfully' };
    }
    async uploadAuthorizedSignature(file) {
        if (!file)
            throw new common_1.NotFoundException('No file uploaded');
        const uploadsDir = path.join(process.cwd(), 'uploads', 'settings');
        await fs.mkdir(uploadsDir, { recursive: true });
        const filename = `authorized-signature-${(0, crypto_1.randomBytes)(16).toString('hex')}${path.extname(file.originalname)}`;
        const filepath = path.join(uploadsDir, filename);
        await fs.writeFile(filepath, file.buffer);
        const relativePath = `/uploads/settings/${filename}`;
        const existingSettings = await this.settingsModel.findOne({ _singleton: 'singleton' }).lean();
        if (existingSettings?.authorizedSignatureUrl) {
            let oldRelativePath;
            try {
                const urlObj = new URL(existingSettings.authorizedSignatureUrl);
                oldRelativePath = urlObj.pathname.replace('/schoolcrmbackend', '');
            }
            catch {
                oldRelativePath = existingSettings.authorizedSignatureUrl;
            }
            const oldPath = path.join(process.cwd(), oldRelativePath.replace(/^\//, ''));
            const allowedDir = path.join(process.cwd(), 'uploads', 'settings');
            const resolvedPath = await fs.realpath(oldPath).catch(() => null);
            if (resolvedPath && resolvedPath.startsWith(allowedDir)) {
                await fs.unlink(resolvedPath).catch(() => { });
            }
        }
        const updated = await this.settingsModel
            .findOneAndUpdate({ _singleton: 'singleton' }, { $set: { authorizedSignatureUrl: relativePath } }, { new: true, upsert: true })
            .lean();
        if (!updated) {
            throw new common_1.NotFoundException('Failed to update authorized signature');
        }
        const fullUrl = (0, url_helper_1.toFullUrl)(relativePath);
        return { authorizedSignatureUrl: fullUrl };
    }
    async deleteAuthorizedSignature() {
        const settings = await this.getSettings();
        if (settings.authorizedSignatureUrl) {
            let relativePath;
            try {
                const urlObj = new URL(settings.authorizedSignatureUrl);
                relativePath = urlObj.pathname.replace('/schoolcrmbackend', '');
            }
            catch {
                relativePath = settings.authorizedSignatureUrl;
            }
            const filepath = path.join(process.cwd(), relativePath.replace(/^\//, ''));
            const allowedDir = path.join(process.cwd(), 'uploads', 'settings');
            const resolvedPath = await fs.realpath(filepath).catch(() => null);
            if (resolvedPath && resolvedPath.startsWith(allowedDir)) {
                await fs.unlink(resolvedPath).catch(() => { });
            }
        }
        await this.settingsModel.findOneAndUpdate({ _singleton: 'singleton' }, { $unset: { authorizedSignatureUrl: 1 } }, { new: true, upsert: true });
        return { message: 'Authorized signature deleted successfully' };
    }
};
exports.SettingsService = SettingsService;
exports.SettingsService = SettingsService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, mongoose_1.InjectModel)(settings_schema_1.Settings.name)),
    __metadata("design:paramtypes", [mongoose_2.Model])
], SettingsService);
//# sourceMappingURL=settings.service.js.map