"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.MailProfileService = void 0;
const api_mail_1 = require("@hed-hog/api-mail");
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 mail_service_1 = require("../mail/mail.service");
let MailProfileService = class MailProfileService {
    constructor(prismaService, paginationService, mailMainService, mailService) {
        this.prismaService = prismaService;
        this.paginationService = paginationService;
        this.mailMainService = mailMainService;
        this.mailService = mailService;
    }
    async list(paginationParams) {
        const fields = ['slug', 'name', 'from_email', 'reply_to_email'];
        const OR = this.prismaService.createInsensitiveSearch(fields, paginationParams);
        return this.paginationService.paginate(this.prismaService.mail_profile, paginationParams, {
            where: OR.length > 0 ? { OR } : {},
            select: {
                id: true,
                slug: true,
                name: true,
                provider: true,
                from_name: true,
                from_email: true,
                reply_to_name: true,
                reply_to_email: true,
                created_at: true,
                updated_at: true,
            },
            orderBy: [{ updated_at: 'desc' }, { id: 'desc' }],
        });
    }
    async get(id) {
        const profile = await this.prismaService.mail_profile.findUnique({
            where: { id },
        });
        if (!profile) {
            throw new common_1.NotFoundException(`Mail profile with id ${id} not found.`);
        }
        return profile;
    }
    async create(data) {
        await this.ensureSlugIsAvailable(data.slug);
        this.validateProviderFields(data);
        return this.prismaService.mail_profile.create({
            data: this.normalizeData(data),
        });
    }
    async update({ id, data }) {
        const existing = await this.prismaService.mail_profile.findUnique({
            where: { id },
        });
        if (!existing) {
            throw new common_1.NotFoundException(`Mail profile with id ${id} not found.`);
        }
        if (data.slug && data.slug !== existing.slug) {
            await this.ensureSlugIsAvailable(data.slug);
        }
        const merged = Object.assign(Object.assign({}, existing), data);
        this.validateProviderFields(merged);
        return this.prismaService.mail_profile.update({
            where: { id },
            data: this.normalizeData(merged),
        });
    }
    async delete({ ids }) {
        if (!(ids === null || ids === void 0 ? void 0 : ids.length)) {
            throw new common_1.BadRequestException('You must select at least one item to delete.');
        }
        return this.prismaService.mail_profile.deleteMany({
            where: {
                id: {
                    in: ids,
                },
            },
        });
    }
    async test(data) {
        this.validateProviderFields(data);
        const normalized = this.normalizeData(data);
        const config = this.buildMailConfig(normalized);
        const destinationEmail = normalized.from_email;
        const sender = normalized.from_name
            ? `${normalized.from_name} <${normalized.from_email}>`
            : normalized.from_email;
        const replyTo = normalized.reply_to_email
            ? normalized.reply_to_name
                ? `${normalized.reply_to_name} <${normalized.reply_to_email}>`
                : normalized.reply_to_email
            : undefined;
        try {
            this.mailMainService.setConfig(config);
            await this.mailMainService.send({
                to: destinationEmail,
                from: sender,
                replyTo,
                subject: `[HedHog] Teste do perfil ${normalized.name}`,
                body: `
          <p>Este e-mail confirma que o perfil <strong>${normalized.name}</strong> foi validado com sucesso.</p>
          <p><strong>Slug:</strong> ${normalized.slug}</p>
          <p><strong>Provedor:</strong> ${normalized.provider}</p>
          <p><strong>Remetente:</strong> ${sender}</p>
        `,
            });
            return {
                success: true,
                destination: destinationEmail,
            };
        }
        finally {
            await this.mailService.reloadConfig().catch(() => undefined);
        }
    }
    async ensureSlugIsAvailable(slug) {
        const existing = await this.prismaService.mail_profile.findUnique({
            where: { slug },
            select: { id: true },
        });
        if (existing) {
            throw new common_1.BadRequestException(`Mail profile with slug "${slug}" already exists.`);
        }
    }
    validateProviderFields(input) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
        const provider = String((_a = input.provider) !== null && _a !== void 0 ? _a : '').toUpperCase();
        if (!provider) {
            throw new common_1.BadRequestException('Provider is required.');
        }
        if (!String((_b = input.from_email) !== null && _b !== void 0 ? _b : '').trim()) {
            throw new common_1.BadRequestException('Sender email is required.');
        }
        switch (provider) {
            case 'SMTP':
                if (!String((_c = input.smtp_host) !== null && _c !== void 0 ? _c : '').trim()) {
                    throw new common_1.BadRequestException('SMTP host is required.');
                }
                if (!input.smtp_port) {
                    throw new common_1.BadRequestException('SMTP port is required.');
                }
                if (!String((_d = input.smtp_username) !== null && _d !== void 0 ? _d : '').trim()) {
                    throw new common_1.BadRequestException('SMTP username is required.');
                }
                if (!String((_e = input.smtp_password) !== null && _e !== void 0 ? _e : '').trim()) {
                    throw new common_1.BadRequestException('SMTP password is required.');
                }
                break;
            case 'GMAIL':
                if (!String((_f = input.gmail_client_id) !== null && _f !== void 0 ? _f : '').trim()) {
                    throw new common_1.BadRequestException('Gmail client ID is required.');
                }
                if (!String((_g = input.gmail_client_secret) !== null && _g !== void 0 ? _g : '').trim()) {
                    throw new common_1.BadRequestException('Gmail client secret is required.');
                }
                if (!String((_h = input.gmail_refresh_token) !== null && _h !== void 0 ? _h : '').trim()) {
                    throw new common_1.BadRequestException('Gmail refresh token is required.');
                }
                break;
            case 'SES':
                if (!String((_j = input.ses_access_key_id) !== null && _j !== void 0 ? _j : '').trim()) {
                    throw new common_1.BadRequestException('SES access key ID is required.');
                }
                if (!String((_k = input.ses_secret_access_key) !== null && _k !== void 0 ? _k : '').trim()) {
                    throw new common_1.BadRequestException('SES secret access key is required.');
                }
                if (!String((_l = input.ses_region) !== null && _l !== void 0 ? _l : '').trim()) {
                    throw new common_1.BadRequestException('SES region is required.');
                }
                break;
            default:
                throw new common_1.BadRequestException(`Invalid provider: ${provider}`);
        }
    }
    normalizeData(input) {
        var _a;
        const provider = String((_a = input.provider) !== null && _a !== void 0 ? _a : '').toUpperCase();
        return {
            slug: this.normalizeString(input.slug),
            name: this.normalizeString(input.name),
            provider,
            from_name: this.normalizeNullableString(input.from_name),
            from_email: this.normalizeString(input.from_email),
            reply_to_name: this.normalizeNullableString(input.reply_to_name),
            reply_to_email: this.normalizeNullableString(input.reply_to_email),
            smtp_host: provider === 'SMTP' ? this.normalizeNullableString(input.smtp_host) : null,
            smtp_port: provider === 'SMTP' && input.smtp_port !== undefined && input.smtp_port !== null
                ? Number(input.smtp_port)
                : null,
            smtp_secure: provider === 'SMTP' ? Boolean(input.smtp_secure) : false,
            smtp_username: provider === 'SMTP' ? this.normalizeNullableString(input.smtp_username) : null,
            smtp_password: provider === 'SMTP' ? this.normalizeNullableString(input.smtp_password) : null,
            gmail_client_id: provider === 'GMAIL' ? this.normalizeNullableString(input.gmail_client_id) : null,
            gmail_client_secret: provider === 'GMAIL'
                ? this.normalizeNullableString(input.gmail_client_secret)
                : null,
            gmail_refresh_token: provider === 'GMAIL'
                ? this.normalizeNullableString(input.gmail_refresh_token)
                : null,
            ses_access_key_id: provider === 'SES' ? this.normalizeNullableString(input.ses_access_key_id) : null,
            ses_secret_access_key: provider === 'SES'
                ? this.normalizeNullableString(input.ses_secret_access_key)
                : null,
            ses_region: provider === 'SES' ? this.normalizeNullableString(input.ses_region) : null,
        };
    }
    buildMailConfig(input) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
        switch (input.provider) {
            case 'SMTP':
                return {
                    global: true,
                    type: 'SMTP',
                    host: (_a = input.smtp_host) !== null && _a !== void 0 ? _a : '',
                    port: (_b = input.smtp_port) !== null && _b !== void 0 ? _b : 587,
                    secure: input.smtp_secure,
                    username: (_c = input.smtp_username) !== null && _c !== void 0 ? _c : '',
                    password: (_d = input.smtp_password) !== null && _d !== void 0 ? _d : '',
                };
            case 'GMAIL':
                return {
                    global: true,
                    type: 'GMAIL',
                    clientId: (_e = input.gmail_client_id) !== null && _e !== void 0 ? _e : '',
                    clientSecret: (_f = input.gmail_client_secret) !== null && _f !== void 0 ? _f : '',
                    refreshToken: (_g = input.gmail_refresh_token) !== null && _g !== void 0 ? _g : '',
                    from: input.from_email,
                };
            case 'SES':
                return {
                    global: true,
                    type: 'SES',
                    region: (_h = input.ses_region) !== null && _h !== void 0 ? _h : '',
                    accessKeyId: (_j = input.ses_access_key_id) !== null && _j !== void 0 ? _j : '',
                    secretAccessKey: (_k = input.ses_secret_access_key) !== null && _k !== void 0 ? _k : '',
                    from: input.from_email,
                };
            default:
                throw new common_1.BadRequestException(`Invalid provider: ${input.provider}`);
        }
    }
    normalizeString(value) {
        return String(value !== null && value !== void 0 ? value : '').trim();
    }
    normalizeNullableString(value) {
        if (value === undefined || value === null) {
            return null;
        }
        const normalized = String(value).trim();
        return normalized.length > 0 ? normalized : null;
    }
};
exports.MailProfileService = MailProfileService;
exports.MailProfileService = MailProfileService = __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_mail_1.MailService))),
    __param(3, (0, common_1.Inject)((0, common_1.forwardRef)(() => mail_service_1.MailService))),
    __metadata("design:paramtypes", [api_prisma_1.PrismaService,
        api_pagination_1.PaginationService,
        api_mail_1.MailService,
        mail_service_1.MailService])
], MailProfileService);
//# sourceMappingURL=mail-profile.service.js.map