const settingHelper = require("../helpers/settingsHelper");
const SettingsHelper = new settingHelper();
const fields = require('../config/configs');
const {form_fields} = fields;
const forms = require("../models/formsModel");
const Forms = new forms;
const Response = require("../helpers/responseHelper");
const { format} = require("date-fns");
const FormSubmissionService = require("../services/FormSubmissionService");

class FormsController {

    async index(req, res) {
        try{
            const forms = await Forms.select('form_submissions');
            const property_types = await SettingsHelper.settings('property_type');
            forms.forEach(form => {
                if(form.property_type){
                    form.property_type = property_types.find(property_type => property_type.id == form.property_type).display;
                }
                form.created_at = format(new Date(form.created_at), "dd/MM/yyyy HH:mm:ss");
            });
            const get_in_touch = forms.filter(form => form.form_type == 'get_in_touch');
            const contact_us = forms.filter(form => form.form_type == 'contact_us');
            const host_page_form = forms.filter(form => form.form_type == 'host_page_form');
            await res.render('forms/list.ejs',{get_in_touch,contact_us,host_page_form});
        }catch(err){
            return Response.error(res, "FORMS_NOT_FOUND", "Forms not found", 400);
        }
    }

    async formSettings(req, res) {
        try{
            const result = await SettingsHelper.formSettings();
            return Response.success(res, result);
        }catch(err){
            return Response.error(res, "SETTINGS_NOT_FOUND", "Settings not found", 400);
        }
    }

    async submitForm(req, res) {
        const { form_type, name, email, phone, property_type, comment } = req.body;

        // Validate using FormSubmissionService
        const validation = FormSubmissionService.validateFormData(req.body);
        if (!validation.valid) {
            return Response.error(res, "VALIDATION_ERROR", validation.error, 400);
        }

        let propertyTypeLabel = '';
        if((form_type === 'get_in_touch' || form_type === 'host_page_form') && property_type){
            try{
                const propertyTypes = await SettingsHelper.settings('property_type');
                const propertyMatch = Array.isArray(propertyTypes)
                    ? propertyTypes.find((property) => `${property.id}` === `${property_type}`)
                    : null;
                propertyTypeLabel = propertyMatch?.display || `${property_type}`;
            }catch(fetchError){
                console.error('Failed to resolve property type display name for enquiry email.', fetchError);
                propertyTypeLabel = `${property_type}`;
            }
        }
        try {
            const fieldValues = {};
            form_fields.forEach(fieldName => {
                if(Object.hasOwnProperty.bind(req.body)(fieldName)){
                    fieldValues[fieldName] = req.body[fieldName];
                }
            });
            await Forms.saveFormDetails(fieldValues);

            // Send email notification via FormSubmissionService (non-blocking)
            const recipients = FormSubmissionService.getRecipients(form_type);
            FormSubmissionService.sendNotificationEmail({
                formType: form_type,
                name,
                email,
                phone,
                propertyTypeLabel,
                comment: comment || '',
                recipients,
            })
                .then((emailDispatched) => {
                    if (!emailDispatched) {
                        console.warn('Form submission stored but notification email was skipped (mail configuration missing).');
                    }
                })
                .catch((emailError) => {
                    console.error('Error sending enquiry notification email (request already succeeded).', emailError);
                });

            return Response.success(res, "Form saved successfully");
        } catch (error) {
            return Response.error(res, "FORM_SAVE_FAILED", "Failed to save form: " + error.message, 500);
        }
    }
}
module.exports = FormsController;
