import type { HttpContext } from '@adonisjs/core/http';
import vine from '@vinejs/vine';
import AppConfig from '#models/appconfig';
import mail from '@adonisjs/mail/services/main';
// import config from '@adonisjs/core/services/config';
// import { configProvider } from '@adonisjs/core';
// import app from '@adonisjs/core/services/app';

export default class MailSettingsController {
    /**
     * Save the email server settings
     */
    public async setMailSettings({ request, response }: HttpContext) {
        const settingsSchema = vine.compile(
            vine.object({
                mail_domain: vine.string(),
                mail_from_address: vine.string(),
                mail_smtp_mode: vine.string(),
                mail_smtpsecure: vine.string().optional(),
                mail_smtphost: vine.string(),
                mail_smtpport: vine.string(),
                mail_smtpauth: vine.boolean(),
                // mail_sendmailmode: vine.string().optional(),
            }),
        );

        const validatedData = await request.validateUsing(settingsSchema);

        const configData: any = { ...validatedData };

        if (!validatedData.mail_smtpauth) {
            configData.mail_smtpname = null;
            configData.mail_smtppassword = null;
        }

        // Prepare the settings to be saved
        const settingsToSave = [
            { appid: 'settings', configkey: 'default', configvalue: validatedData.mail_smtp_mode, type: 1, lazy: 0 },
            { appid: 'settings', configkey: 'host', configvalue: validatedData.mail_smtphost, type: 1, lazy: 0 },
            { appid: 'settings', configkey: 'port', configvalue: validatedData.mail_smtpport, type: 1, lazy: 0 },
            {
                appid: 'settings',
                configkey: 'from.address',
                configvalue: `${validatedData.mail_from_address}@${validatedData.mail_domain}`,
                type: 1,
                lazy: 0,
            },
        ];

        // if (validatedData.mail_smtpauth) {
        //     settingsToSave.push(
        //         { appid: 'settings', configkey: 'smtp_user', configvalue: validatedData.mail_smtpname, type: 1, lazy: 0 },
        //         { appid: 'settings', configkey: 'smtp_password', configvalue: validatedData.mail_smtppassword, type: 1, lazy: 0 },
        //     );
        // } else {
        //     settingsToSave.push(
        //         { appid: 'settings', configkey: 'smtp_user', configvalue: null, type: 1, lazy: 0 },
        //         { appid: 'settings', configkey: 'smtp_password', configvalue: null, type: 1, lazy: 0 },
        //     );
        // }

        // Save or update the settings in the database
        for (const setting of settingsToSave) {
            await AppConfig.updateOrCreate(
                { appid: setting.appid, configkey: setting.configkey },
                { configvalue: setting.configvalue, type: setting.type, lazy: setting.lazy },
            );
        }

        return response.json({ success: true, message: 'Mail settings updated successfully' });
    }

    /**
     * Send a test email to ensure settings work
     */
    public async sendTestMail({ response, auth }: HttpContext) {
        const user = auth.user!;
        const userEmail = user.email;
        
        // let mailManager = await app.container.make('mail.manager');
        // let iwas = mailManager.use();       
        // let test = mail.config.mailers.smtp();
        if (!userEmail) {
            return response.badRequest({ message: 'User email is not set. Please update your profile.' });
        }

        try {
            await mail.send((message) => {
                message
                    // .from(Config.get('mail.from.address'))
                    .from('tethys@geosphere.at')
                    .to(userEmail)
                    .subject('Test Email')
                    .html('<p>If you received this email, the email configuration seems to be correct.</p>');
            });

            return response.json({ success: true, message: 'Test email sent successfully' });
            // return response.flash('Test email sent successfully!', 'message').redirect().back();
        } catch (error) {
            return response.internalServerError({ message: `Error sending test email: ${error.message}` });
        }
    }
}
