"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); }
};
var SettingService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SettingService = void 0;
const api_1 = require("@hed-hog/api");
const api_locale_1 = require("@hed-hog/api-locale");
const api_pagination_1 = require("@hed-hog/api-pagination");
const api_prisma_1 = require("@hed-hog/api-prisma");
const common_1 = require("@nestjs/common");
const pako = __importStar(require("pako"));
const integration_developer_api_service_1 = require("../integration/services/integration-developer-api.service");
let SettingService = SettingService_1 = class SettingService {
    constructor(prismaService, paginationService, localeService, integrationApi) {
        this.prismaService = prismaService;
        this.paginationService = paginationService;
        this.localeService = localeService;
        this.integrationApi = integrationApi;
        this.logger = new common_1.Logger(SettingService_1.name);
        this.cachedSettings = {};
    }
    async exportSettings(includeSecrets = false) {
        const settings = await this.prismaService.setting.findMany({
            where: Object.assign({}, (!includeSecrets ? {
                NOT: [
                    { type: api_prisma_1.setting_type_0f055cd5ea_enum.secret },
                ],
            } : {})),
            select: {
                slug: true,
                value: true,
            }
        });
        // Converte para JSON e compacta com gzip
        const jsonString = JSON.stringify(settings);
        const compressed = pako.gzip(jsonString);
        return Buffer.from(compressed);
    }
    async importSettings(locale, file) {
        this.clearCache();
        let json;
        try {
            // Descompacta o arquivo .hedhog
            const decompressed = pako.ungzip(file.buffer, { to: 'string' });
            json = JSON.parse(decompressed);
        }
        catch (err) {
            throw new common_1.BadRequestException((0, api_locale_1.getLocaleText)('invalidCompressedFile', locale, 'File is not a valid .hedhog file or is corrupted.'));
        }
        if (!Array.isArray(json)) {
            throw new common_1.BadRequestException((0, api_locale_1.getLocaleText)('invalidJsonArray', locale, 'The JSON file must contain an array of settings.'));
        }
        const slugsFromFile = json.map((item) => item.slug).filter(Boolean);
        const existingSettings = await this.prismaService.setting.findMany({
            where: {
                slug: {
                    in: slugsFromFile,
                },
            },
            select: {
                slug: true,
            },
        });
        const existingSlugs = existingSettings.map((s) => s.slug);
        const validSlugs = slugsFromFile.filter((slug) => existingSlugs.includes(slug));
        const invalidSlugs = slugsFromFile.filter((slug) => !existingSlugs.includes(slug));
        // Filtra apenas os dados válidos para retornar
        const validData = json.filter((item) => validSlugs.includes(item.slug));
        return {
            totalSettings: slugsFromFile.length,
            validSettings: validSlugs.length,
            invalidSlugs,
            validSlugs,
            fileData: validData,
        };
    }
    async confirmImport(settings) {
        this.clearCache();
        const slugs = settings.map((s) => s.slug);
        const existingSettings = await this.prismaService.setting.findMany({
            where: {
                slug: {
                    in: slugs,
                },
            },
            select: {
                id: true,
                slug: true,
                type: true,
                value: true,
            },
        });
        const transaction = [];
        const changedSettings = [];
        for (const setting of settings) {
            const existingSetting = existingSettings.find((s) => s.slug === setting.slug);
            if (existingSetting) {
                const nextValue = this.setValueFormattedByType(existingSetting.type, setting.value);
                transaction.push(this.prismaService.setting.update({
                    where: {
                        id: existingSetting.id,
                    },
                    data: {
                        value: nextValue,
                    },
                }));
                changedSettings.push({
                    settingId: existingSetting.id,
                    slug: existingSetting.slug,
                    type: existingSetting.type,
                    oldValue: existingSetting.value,
                    newValue: nextValue,
                    source: 'confirmImport',
                });
            }
        }
        if (transaction.length > 0) {
            await this.prismaService.$transaction(transaction);
            await this.emitSettingChangedEvents(changedSettings);
        }
        return {
            success: true,
            updatedCount: transaction.length,
        };
    }
    async getSystemSettings() {
        const locales = await this.localeService.getEnables();
        const slugs = [
            'system-name',
            'system-slogan',
            'icon-url',
            'image-url',
            'theme-primary-light',
            'theme-primary-foreground-light',
            'theme-secondary-light',
            'theme-secondary-foreground-light',
            'theme-accent-light',
            'theme-accent-foreground-light',
            'theme-muted-light',
            'theme-muted-foreground-light',
            'theme-background-light',
            'theme-background-foreground-light',
            'theme-card-light',
            'theme-card-foreground-light',
            'theme-primary-dark',
            'theme-primary-foreground-dark',
            'theme-secondary-dark',
            'theme-secondary-foreground-dark',
            'theme-accent-dark',
            'theme-accent-foreground-dark',
            'theme-muted-dark',
            'theme-muted-foreground-dark',
            'theme-background-dark',
            'theme-background-foreground-dark',
            'theme-card-dark',
            'theme-card-foreground-dark',
            'theme-radius',
            'theme-font',
            'theme-text-size',
            'theme-mode',
            'password-min-symbols',
            'password-min-numbers',
            'password-min-uppercase',
            'password-min-length',
            'mfa-email-code-length',
            'ai-openai-api-key-enabled',
            'ai-gemini-api-key-enabled',
            'mcp-enabled',
            'date-format',
            'time-format',
            'timezone',
            'menu-width',
            'providers',
            'disable-authentication-with-email-and-password',
            'contact-allow-company-registration',
            'operations.comment-edit-window',
            'lms-video-conversion-enabled',
            'lms-video-frame-capture-interval-seconds',
        ];
        const setting = await this.getSettingValues(slugs);
        return { locales, setting };
    }
    async getEffectiveSettings(userId) {
        var _a;
        const { locales, setting } = await this.getSystemSettings();
        const userSettings = await this.getUserSettings(userId);
        for (const userSetting of userSettings) {
            const slug = (_a = userSetting.setting) === null || _a === void 0 ? void 0 : _a.slug;
            if (!slug)
                continue;
            const value = userSetting.value;
            if (value === undefined || value === null)
                continue;
            const globalValue = setting === null || setting === void 0 ? void 0 : setting[slug];
            const globalType = typeof globalValue;
            if (globalType === 'boolean') {
                setting[slug] = value === 'true';
                continue;
            }
            if (globalType === 'number') {
                const parsed = Number(value);
                setting[slug] = Number.isNaN(parsed) ? value : parsed;
                continue;
            }
            if (Array.isArray(globalValue) || globalType === 'object') {
                try {
                    setting[slug] = JSON.parse(value);
                }
                catch (_b) {
                    setting[slug] = value;
                }
                continue;
            }
            setting[slug] = value;
        }
        return { locales, setting };
    }
    async setManySettings(data) {
        this.clearCache();
        const transaction = [];
        const existingSettings = await this.prismaService.setting.findMany({
            where: {
                slug: {
                    in: data.setting.map((item) => item.slug),
                },
            },
            select: {
                id: true,
                slug: true,
                type: true,
                value: true,
            },
        });
        const changedSettings = [];
        for (const { slug, value } of data.setting) {
            const existingSetting = existingSettings.find((item) => item.slug === slug);
            if (!existingSetting) {
                continue;
            }
            const nextValue = this.setValueFormattedByType(existingSetting.type, value);
            transaction.push(this.prismaService.setting.updateMany({
                where: {
                    slug,
                },
                data: {
                    value: nextValue,
                },
            }));
            changedSettings.push({
                settingId: existingSetting.id,
                slug: existingSetting.slug,
                type: existingSetting.type,
                oldValue: existingSetting.value,
                newValue: nextValue,
                source: 'setManySettings',
            });
        }
        await this.prismaService.$transaction(transaction);
        await this.emitSettingChangedEvents(changedSettings);
        return { success: true };
    }
    async getSettingFromGroup(locale, paginationParams, slug, userId) {
        const fields = ['slug', 'value'];
        paginationParams.pageSize = 100;
        const OR = this.prismaService.createInsensitiveSearch(fields, paginationParams);
        const result = await this.paginationService.paginate(this.prismaService.setting, paginationParams, {
            where: {
                AND: {
                    setting_group: {
                        slug,
                    },
                    OR,
                },
            },
            include: {
                setting_group: {
                    include: {
                        setting_group_locale: {
                            where: {
                                locale: {
                                    code: locale,
                                },
                            },
                            select: {
                                name: true,
                                description: true,
                            },
                        },
                    },
                },
                setting_subgroup: {
                    include: {
                        setting_subgroup_locale: {
                            where: {
                                locale: {
                                    code: locale,
                                },
                            },
                            select: {
                                name: true,
                                description: true,
                            },
                        },
                    },
                },
                setting_locale: {
                    where: {
                        locale: {
                            code: locale,
                        },
                    },
                    select: {
                        name: true,
                        description: true,
                    },
                },
                setting_list: {
                    select: {
                        id: true,
                        order: true,
                        value: true,
                    },
                    orderBy: {
                        order: 'asc',
                    },
                },
                setting_user: {
                    where: {
                        user_id: userId,
                    },
                    select: {
                        setting_id: true,
                        value: true,
                    },
                },
            },
        }, 'setting_locale');
        result.data = result.data.map((setting) => {
            var _a, _b, _c, _d;
            setting.setting_group = (0, api_1.itemTranslations)('setting_group_locale', setting.setting_group);
            if (setting.setting_subgroup) {
                setting.setting_subgroup = (0, api_1.itemTranslations)('setting_subgroup_locale', setting.setting_subgroup);
            }
            (_a = setting.subgroupId) !== null && _a !== void 0 ? _a : (setting.subgroupId = (_d = (_b = setting.subgroup_id) !== null && _b !== void 0 ? _b : (_c = setting.setting_subgroup) === null || _c === void 0 ? void 0 : _c.id) !== null && _d !== void 0 ? _d : null);
            return setting;
        });
        return result;
    }
    async listSettingGroups(locale, paginationParams) {
        const fields = ['slug', 'icon'];
        paginationParams.pageSize = 100;
        const OR = this.prismaService.createInsensitiveSearch(fields, paginationParams);
        const result = await this.paginationService.paginate(this.prismaService.setting_group, paginationParams, {
            where: {
                slug: {
                    not: 'hidden',
                },
                OR,
            },
            include: {
                setting_group_locale: {
                    where: {
                        locale: {
                            code: locale,
                        },
                    },
                    select: {
                        name: true,
                        description: true,
                    },
                },
            },
        }, 'setting_group_locale');
        return result;
    }
    async listSettings(locale, paginationParams) {
        const fields = ['slug', 'value'];
        const OR = this.prismaService.createInsensitiveSearch(fields, paginationParams);
        const result = await this.paginationService.paginate(this.prismaService.setting, paginationParams, {
            where: {
                OR,
            },
            include: {
                setting_group: {
                    include: {
                        setting_group_locale: {
                            where: {
                                locale: {
                                    code: locale,
                                },
                            },
                            select: {
                                name: true,
                                description: true,
                            },
                        },
                    },
                },
                setting_subgroup: {
                    include: {
                        setting_subgroup_locale: {
                            where: {
                                locale: {
                                    code: locale,
                                },
                            },
                            select: {
                                name: true,
                                description: true,
                            },
                        },
                    },
                },
                setting_locale: {
                    where: {
                        locale: {
                            code: locale,
                        },
                    },
                    select: {
                        name: true,
                        description: true,
                    },
                },
                setting_list: {
                    select: {
                        id: true,
                        order: true,
                        value: true,
                    },
                    orderBy: {
                        order: 'asc',
                    },
                },
            },
        }, 'setting_locale');
        result.data = result.data.map((setting) => {
            var _a, _b, _c, _d;
            setting.setting_group = (0, api_1.itemTranslations)('setting_group_locale', setting.setting_group);
            if (setting.setting_subgroup) {
                setting.setting_subgroup = (0, api_1.itemTranslations)('setting_subgroup_locale', setting.setting_subgroup);
            }
            (_a = setting.subgroupId) !== null && _a !== void 0 ? _a : (setting.subgroupId = (_d = (_b = setting.subgroup_id) !== null && _b !== void 0 ? _b : (_c = setting.setting_subgroup) === null || _c === void 0 ? void 0 : _c.id) !== null && _d !== void 0 ? _d : null);
            return setting;
        });
        return result;
    }
    async updateSettingListOptions(settingId, data) {
        var _a, _b;
        this.clearCache();
        const setting = await this.prismaService.setting.findUnique({
            where: { id: settingId },
            select: {
                id: true,
                component: true,
            },
        });
        if (!setting) {
            throw new common_1.NotFoundException(`Setting with ID ${settingId} not found.`);
        }
        const component = String((_a = setting.component) !== null && _a !== void 0 ? _a : '').toLowerCase();
        if (component !== 'combobox' && component !== 'checkbox') {
            throw new common_1.BadRequestException('Only combobox and checkbox settings support list options.');
        }
        const options = ((_b = data.options) !== null && _b !== void 0 ? _b : [])
            .map((option, index) => {
            var _a, _b, _c;
            return ({
                value: (_b = (_a = option.value) === null || _a === void 0 ? void 0 : _a.trim()) !== null && _b !== void 0 ? _b : '',
                order: (_c = option.order) !== null && _c !== void 0 ? _c : index + 1,
            });
        })
            .filter((option) => option.value.length > 0);
        const updatedSetting = await this.prismaService.setting.update({
            where: { id: settingId },
            data: {
                setting_list: {
                    deleteMany: {},
                    create: options,
                },
            },
            include: {
                setting_list: {
                    select: {
                        id: true,
                        order: true,
                        value: true,
                    },
                    orderBy: {
                        order: 'asc',
                    },
                },
            },
        });
        return updatedSetting;
    }
    async get(settingId) {
        const setting = await this.prismaService.setting.findUnique({
            where: { id: settingId },
        });
        if (!setting) {
            throw new common_1.NotFoundException(`Setting with ID ${settingId} not found.`);
        }
        return setting;
    }
    async create(data, _locale) {
        this.clearCache();
        const createdSetting = await this.prismaService.setting.create({
            data: {
                slug: data.slug,
                type: data.type,
                value: this.setValueFormattedByType(data.type, data.value),
                user_override: data.user_override,
                setting_group: {
                    connect: {
                        id: data.group_id,
                    },
                },
            },
        });
        await this.emitSettingChangedEvents([
            {
                settingId: createdSetting.id,
                slug: createdSetting.slug,
                type: createdSetting.type,
                oldValue: undefined,
                newValue: createdSetting.value,
                source: 'create',
            },
        ]);
        return createdSetting;
    }
    async update({ id, data }) {
        this.clearCache();
        const currentSetting = await this.prismaService.setting.findFirst({
            where: {
                id,
            },
            select: {
                id: true,
                slug: true,
                type: true,
                value: true,
            },
        });
        if (!(currentSetting === null || currentSetting === void 0 ? void 0 : currentSetting.type)) {
            throw new common_1.NotFoundException(`Setting not found.`);
        }
        const { type } = currentSetting;
        // Build update data object with only provided fields
        const updateData = {};
        if (data.slug !== undefined) {
            updateData.slug = data.slug;
        }
        if (data.type !== undefined) {
            updateData.type = data.type;
        }
        if (data.value !== undefined) {
            updateData.value = this.setValueFormattedByType(data.type || type, data.value);
        }
        if (data.user_override !== undefined) {
            updateData.user_override = data.user_override;
        }
        if (data.component !== undefined) {
            updateData.component = data.component;
        }
        if (data.group_id !== undefined) {
            updateData.setting_group = {
                connect: {
                    id: data.group_id,
                },
            };
        }
        const updatedSetting = await this.prismaService.setting.update({
            where: { id },
            data: updateData,
        });
        await this.emitSettingChangedEvents([
            {
                settingId: updatedSetting.id,
                slug: updatedSetting.slug,
                type: updatedSetting.type,
                oldValue: currentSetting.value,
                newValue: updatedSetting.value,
                source: 'update',
            },
        ]);
        // Garantir que o value sobrescreve o valor original
        const result = Object.assign({}, updatedSetting);
        result.value = this.getValueFormattedByType(updatedSetting.type, updatedSetting.value);
        return result;
    }
    async updateFromSlug(slug, data) {
        this.clearCache();
        const currentSetting = await this.prismaService.setting.findFirst({
            where: {
                slug,
            },
            select: {
                id: true,
                slug: true,
                type: true,
                value: true,
            },
        });
        if (!(currentSetting === null || currentSetting === void 0 ? void 0 : currentSetting.id)) {
            throw new common_1.NotFoundException(`Setting with slug ${slug} not found.`);
        }
        const nextValue = this.setValueFormattedByType(currentSetting.type, data.value);
        const updatedSetting = await this.prismaService.setting.update({
            where: { id: currentSetting.id },
            data: {
                value: nextValue,
            },
        });
        await this.emitSettingChangedEvents([
            {
                settingId: updatedSetting.id,
                slug: updatedSetting.slug,
                type: updatedSetting.type,
                oldValue: currentSetting.value,
                newValue: updatedSetting.value,
                source: 'updateFromSlug',
            },
        ]);
        const result = Object.assign({}, updatedSetting);
        result.value = this.getValueFormattedByType(updatedSetting.type, updatedSetting.value);
        return result;
    }
    normalizeValueForComparison(value) {
        if (value === undefined) {
            return '__undefined__';
        }
        if (value === null) {
            return null;
        }
        if (typeof value === 'string') {
            return value.trim();
        }
        try {
            return JSON.stringify(value);
        }
        catch (_a) {
            return String(value);
        }
    }
    isValueDefined(value) {
        if (value === undefined || value === null) {
            return false;
        }
        if (typeof value === 'string') {
            return value.trim().length > 0;
        }
        if (Array.isArray(value)) {
            return value.length > 0;
        }
        return true;
    }
    async emitSettingChangedEvents(changes) {
        const events = changes
            .filter((change) => Boolean(change.slug))
            .filter((change) => this.normalizeValueForComparison(change.oldValue) !==
            this.normalizeValueForComparison(change.newValue))
            .map((change) => {
            var _a, _b, _c;
            return ({
                eventName: 'core.setting.changed',
                sourceModule: 'core',
                aggregateType: 'setting',
                aggregateId: String((_a = change.settingId) !== null && _a !== void 0 ? _a : change.slug),
                payload: {
                    settingId: (_b = change.settingId) !== null && _b !== void 0 ? _b : null,
                    slug: change.slug,
                    type: (_c = change.type) !== null && _c !== void 0 ? _c : null,
                    source: change.source,
                    hasValue: this.isValueDefined(change.newValue),
                },
                metadata: {
                    settingSlug: change.slug,
                    source: change.source,
                },
            });
        });
        if (events.length === 0) {
            return;
        }
        try {
            await this.integrationApi.publishEvents(events);
        }
        catch (error) {
            this.logger.error(`Failed to publish ${events.length} setting change event(s).`, error instanceof Error ? error.stack : String(error));
        }
    }
    setValueFormattedByType(type, value) {
        switch (type) {
            case 'boolean':
                return value === true || value === 'true' ? 'true' : 'false';
            case 'number':
                return Number(value).toString();
            case 'array':
            case 'json':
                return typeof value === 'string' ? value : JSON.stringify(value);
            default:
                return value;
        }
    }
    getValueFormattedByType(type, value) {
        switch (type) {
            case 'boolean':
                return value === true || value === 'true' ? 'true' : 'false';
            case 'number':
                return Number(value).toString();
            case 'array':
            case 'json':
                return typeof value === 'string' ? value : JSON.stringify(value);
            default:
                return value;
        }
    }
    async delete(locale, { ids }) {
        this.clearCache();
        if (ids == undefined || ids == null) {
            throw new common_1.BadRequestException(`You must select at least one setting to delete.`);
        }
        const existingSettings = await this.prismaService.setting.findMany({
            where: {
                id: {
                    in: ids,
                },
            },
            select: {
                id: true,
            },
        });
        if (existingSettings.length !== ids.length) {
            throw new common_1.BadRequestException((0, api_locale_1.getLocaleText)('someSettingsNotFound', locale, `Some settings were not found.`));
        }
        return this.prismaService.setting.deleteMany({
            where: {
                id: {
                    in: ids,
                },
            },
        });
    }
    async setSettingUserValue(locale, user_id, slug, value) {
        this.clearCache();
        const user = await this.prismaService.user.findUnique({
            where: {
                id: user_id,
            },
            select: {
                id: true,
            },
        });
        if (!user) {
            throw new common_1.NotFoundException((0, api_locale_1.getLocaleText)('userNotFound', locale, `User not found.`));
        }
        const setting = await this.prismaService.setting.findFirst({
            where: {
                slug,
                user_override: true,
            },
        });
        if (!setting) {
            throw new common_1.NotFoundException((0, api_locale_1.getLocaleText)('settingNotFound', locale, `Setting not found or user can not override.`));
        }
        return await this.prismaService.setting_user.upsert({
            where: {
                user_id_setting_id: {
                    setting_id: setting.id,
                    user_id: user.id,
                },
            },
            create: {
                setting_id: setting.id,
                value,
                user_id: user.id,
            },
            update: {
                value,
            },
            select: {
                setting_id: true,
                user_id: true,
                value: true,
            },
        });
    }
    async getSettingValues(slug, userId) {
        const slugs = Array.isArray(slug) ? slug : [slug];
        if (userId === undefined &&
            this.cachedSettings &&
            slugs.every(s => Object.prototype.hasOwnProperty.call(this.cachedSettings, s))) {
            // Retorna apenas os slugs requisitados do cache
            const cached = {};
            slugs.forEach(s => {
                cached[s] = this.cachedSettings[s];
            });
            return cached;
        }
        slug = Array.isArray(slug) ? slug : [slug];
        let setting = await this.prismaService.setting.findMany({
            where: {
                slug: {
                    in: slug,
                },
            },
            select: {
                id: true,
                value: true,
                slug: true,
                type: true,
                user_override: true,
            },
        });
        const slugUserOverride = setting.filter((s) => s.user_override);
        const settingUser = userId === undefined
            ? []
            : await this.prismaService.setting_user.findMany({
                where: {
                    user_id: userId,
                    setting_id: {
                        in: slugUserOverride.map((setting) => setting === null || setting === void 0 ? void 0 : setting.id),
                    },
                },
                select: {
                    value: true,
                    setting_id: true,
                },
            });
        const data = {};
        const cacheData = {};
        for (const s of setting) {
            switch (s.type) {
                case 'boolean':
                    data[s.slug] = s.value === 'true';
                    cacheData[s.slug] = s.value === 'true';
                    break;
                case 'number':
                    data[s.slug] = Number(s.value);
                    cacheData[s.slug] = Number(s.value);
                    break;
                case 'array':
                case 'json':
                    try {
                        data[s.slug] = JSON.parse(s.value);
                        cacheData[s.slug] = JSON.parse(s.value);
                    }
                    catch (err) {
                        console.error('Error parsing JSON', s.value, err);
                        data[s.slug] = s.value;
                        cacheData[s.slug] = s.value;
                    }
                    break;
                default:
                    data[s.slug] = s.value;
                    cacheData[s.slug] = s.value;
            }
        }
        // sobrescreve os valores em data, mas NÃO salva no cache
        settingUser.forEach((ss) => {
            var _a;
            const slugOverride = (_a = slugUserOverride.find((s) => s.id === ss.setting_id)) === null || _a === void 0 ? void 0 : _a.slug;
            if (slugOverride) {
                data[slugOverride] = ss.value;
            }
        });
        this.setCache(cacheData);
        return data;
    }
    setCache(value) {
        Object.keys(value).forEach(key => {
            this.cachedSettings[key] = value[key];
        });
        return this.cachedSettings;
    }
    clearCache() {
        this.cachedSettings = {};
    }
    async getUserSettings(user_id) {
        const user = await this.prismaService.user.findUnique({
            where: {
                id: user_id,
            },
            select: {
                id: true,
            },
        });
        if (!user) {
            throw new common_1.NotFoundException(`User not found.`);
        }
        return this.prismaService.setting_user.findMany({
            where: {
                user_id,
            },
            include: {
                setting: {
                    select: {
                        slug: true,
                    },
                },
            },
        });
    }
    async setValue(slug, value) {
        this.clearCache();
        const currentSetting = await this.prismaService.setting.findFirst({
            where: {
                slug,
            },
            select: {
                id: true,
                slug: true,
                type: true,
                value: true,
            },
        });
        if (!(currentSetting === null || currentSetting === void 0 ? void 0 : currentSetting.id)) {
            throw new common_1.NotFoundException(`Setting with slug ${slug} not found.`);
        }
        const nextValue = this.setValueFormattedByType(currentSetting.type, value);
        const result = await this.prismaService.setting.updateMany({
            where: {
                slug,
            },
            data: {
                value: nextValue,
            },
        });
        await this.emitSettingChangedEvents([
            {
                settingId: currentSetting.id,
                slug: currentSetting.slug,
                type: currentSetting.type,
                oldValue: currentSetting.value,
                newValue: nextValue,
                source: 'setValue',
            },
        ]);
        return result;
    }
};
exports.SettingService = SettingService;
exports.SettingService = SettingService = SettingService_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, common_1.Inject)((0, common_1.forwardRef)(() => api_prisma_1.PrismaService))),
    __param(1, (0, common_1.Inject)((0, common_1.forwardRef)(() => api_pagination_1.PaginationService))),
    __param(2, (0, common_1.Inject)((0, common_1.forwardRef)(() => api_locale_1.LocaleService))),
    __param(3, (0, common_1.Inject)((0, common_1.forwardRef)(() => integration_developer_api_service_1.IntegrationDeveloperApiService))),
    __metadata("design:paramtypes", [api_prisma_1.PrismaService,
        api_pagination_1.PaginationService,
        api_locale_1.LocaleService,
        integration_developer_api_service_1.IntegrationDeveloperApiService])
], SettingService);
//# sourceMappingURL=setting.service.js.map