import { Injectable, Logger, Inject, BadRequestException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import type { Cache } from 'cache-manager';
import * as nodemailer from 'nodemailer';
import { CmsService } from '../cms/cms.service';
import { v4 as uuidv4 } from 'uuid';

export interface ContactMailData {
    name: string;
    email: string;
    type: string;
    details: string;
    captchaId: string;
    captchaAnswer: string;
}

@Injectable()
export class MailService {
    private readonly logger = new Logger(MailService.name);
    private transporter: nodemailer.Transporter;

    constructor(
        private configService: ConfigService,
        private cmsService: CmsService,
        @Inject(CACHE_MANAGER) private cacheManager: Cache,
    ) {
        this.initTransporter();
    }

    async generateCaptcha() {
        const num1 = Math.floor(Math.random() * 10) + 1;
        const num2 = Math.floor(Math.random() * 10) + 1;
        const answer = num1 + num2;
        const id = uuidv4();

        await this.cacheManager.set(`captcha:${id}`, answer.toString(), 300000); // 5 mins

        return {
            id,
            question: `${num1} + ${num2} = ?`,
        };
    }

    async verifyCaptcha(id: string, answer: string) {
        const cachedAnswer = await this.cacheManager.get(`captcha:${id}`);
        if (!cachedAnswer) {
            throw new BadRequestException('Captcha expired or invalid');
        }

        if (String(cachedAnswer) !== String(answer).trim()) {
            throw new BadRequestException('Incorrect captcha answer');
        }

        await this.cacheManager.del(`captcha:${id}`);
        return true;
    }

    private initTransporter(customConfig?: any) {
        this.transporter = nodemailer.createTransport({
            host: customConfig?.host || this.configService.get<string>('MAIL_HOST'),
            port: customConfig?.port || this.configService.get<number>('MAIL_PORT', 587),
            secure: customConfig?.secure === 'true' || customConfig?.secure === true,
            auth: {
                user: customConfig?.user || this.configService.get<string>('MAIL_USER'),
                pass: customConfig?.pass || this.configService.get<string>('MAIL_PASSWORD'),
            },
        });
    }

    async sendContactMail(data: ContactMailData) {
        // Verify Captcha
        await this.verifyCaptcha(data.captchaId, data.captchaAnswer);

        const isMailEnabled = this.configService.get<boolean>('features.mail', false);

        // Alıcı mailini veritabanından veya varsayılandan al
        const settings = await this.cmsService.findContentBySection('mail_settings', 'tr');
        const targetEmail = settings?.targetEmail || 'haruncanmedia@gmail.com';

        if (!isMailEnabled) {
            this.logger.warn('📧 Mail service is disabled. Message not sent, but logged:');
            this.logger.log(`TO: ${targetEmail}, FROM: ${data.name} <${data.email}>, TYPE: ${data.type}, MESSAGE: ${data.details}`);
            return { success: true, message: 'Mail dev-mode: logged to console' };
        }

        // Eğer veritabanında SMTP ayarları varsa transporter'ı güncelle
        if (settings && settings.host && settings.user && settings.pass) {
            this.logger.log('📧 Using dynamic SMTP settings from database');
            this.initTransporter(settings);
        }

        try {
            const info = await this.transporter.sendMail({
                from: settings?.from || this.configService.get<string>('MAIL_FROM', '"HarunCAN Studio" <noreply@haruncan.com>'),
                to: targetEmail,
                subject: `New Contact Form Message from ${data.name}`,
                text: `Name: ${data.name}\nEmail: ${data.email}\nInquiry Type: ${data.type}\nDetails: ${data.details}`,
                html: `
          <div style="font-family: sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e2e8f0; border-radius: 8px;">
            <h2 style="color: #FF5733; border-bottom: 2px solid #FF5733; padding-bottom: 10px;">New Contact Form Submission</h2>
            <p><strong>Name:</strong> ${data.name}</p>
            <p><strong>Email:</strong> ${data.email}</p>
            <p><strong>Inquiry Type:</strong> ${data.type}</p>
            <div style="background: #f8fafc; padding: 15px; border-left: 4px solid #FF5733; margin-top: 20px;">
              <p style="margin: 0; color: #475569;"><strong>Message Details:</strong></p>
              <p style="margin-top: 10px; line-height: 1.6;">${data.details.replace(/\n/g, '<br>')}</p>
            </div>
            <p style="font-size: 12px; color: #94a3b8; margin-top: 30px; border-top: 1px solid #e2e8f0; padding-top: 10px;">
              Sent from HarunCAN Studio Contact Form
            </p>
          </div>
        `,
            });

            this.logger.log(`📧 Contact mail sent: ${info.messageId}`);
            return { success: true, messageId: info.messageId };
        } catch (error) {
            this.logger.error('❌ Failed to send contact mail:', error);
            throw error;
        }
    }
}
