const InternalForms = require("../../models/InternalForms");
const InternalFormsFields = require("../../models/InternalFormFields");
const InternalFormFieldsDependentInputs = require("../../models/InternalFormFieldsDependentInputs");
const CustomFieldsTypes = require("../../models/CustomFieldsTypes");
const Sequelize = require("sequelize");
const {
  generateRandomNumber,
  generateRandomString,
  removeSpecialCharactersAndSpaces,
} = require("../../helpers/common");

exports.getCustomFields = (req, res, next) => {
  const { internalFormId } = req.query;

  InternalForms.findByPk(internalFormId, {
    include: [
      {
        model: InternalFormsFields,
        as: "internal_form_fields",
        include: [
          {
            model: InternalFormFieldsDependentInputs,
            as: "internal_form_fields_dependent_input",
            include: [
              {
                model: CustomFieldsTypes,
                as: "custom_field_type",
                attributes: {
                  exclude: ["createdAt", "updatedAt"],
                },
              },
            ],
          },
          {
            model: CustomFieldsTypes,
            as: "custom_field_type",
            attributes: {
              exclude: ["createdAt", "updatedAt"],
            },
          },
        ],
      },
    ],
  })
    .then((internalForm) => {
      if (!internalForm) {
        return res
          .status(404)
          .json({ success: false, msg: "Internal form Id not found." });
      }
      const { form_title, form_sub_title } = internalForm;

      res.status(200).json({ success: true, internalForm });
    })
    .catch((err) => {
      next(err);
    });
};

exports.createInternalForm = async (req, res, next) => {
  try {
    const { form_title, form_sub_title, form_fields } = req.body;

    const internalForm = await InternalForms.create({
      form_title,
      form_sub_title,
    });

    for (const formField of form_fields) {
      const {
        field_type_id,
        field_name,
        is_required,
        default_value,
        options,
        dependent_fields,
        unique_code,
        sort_order,
      } = formField;

      const code =
        generateRandomNumber() +
        `-${removeSpecialCharactersAndSpaces(field_name)}-` +
        generateRandomString();
      const defaultValue = default_value ? default_value : "";
      const _options = options ? options.join("||") : "";
      const uniqueCode = unique_code ? unique_code : "";
      const sortOrder = sort_order ? sort_order : null;

      const hasDependentFields = dependent_fields
        ? Object.keys(dependent_fields).length > 0 &&
          dependent_fields.fields.length > 0
        : false;

      const internalFormField = await InternalFormsFields.create({
        code: code,
        internal_form_id: internalForm.id,
        custom_field_type_id: field_type_id,
        field_name,
        is_required,
        default_value: defaultValue,
        options: _options,
        unique_code: uniqueCode,
        sort_order: sortOrder,
        has_dependent_fields: hasDependentFields,
      });

      if (hasDependentFields) {
        const dependentFieldInputs = dependent_fields.fields.map(
          ({
            unique_code,
            field_type_id,
            field_name,
            is_required,
            auto_compute,
            option,
            hierarchy,
            sort_order,
          }) => {
            const isAutoCompute = auto_compute
              ? Object.keys(auto_compute).length > 0
              : false;

            let formula = null;
            if (isAutoCompute) {
              const { formula: _formula } = auto_compute;
              formula = _formula;
            }

            return {
              internal_form_field_id: internalFormField.id,
              same_hierarchy: hierarchy === "same",
              unique_code,
              field_type_id,
              field_name,
              is_required,
              option,
              sort_order,
              is_autocompute: isAutoCompute,
              formula,
            };
          }
        );

        InternalFormFieldsDependentInputs.bulkCreate(dependentFieldInputs);
      }
    }
    res.status(201).json({
      internalFormId: internalForm.id,
      success: true,
    });
  } catch (error) {
    console.error("Error creating internal form:", error);
    res.status(500).json({ message: "Internal server error" });
  }
};

exports.createCustomFields = (req, res, next) => {
  const customFieldsData = req.body.map(
    ({ data_input_type, data_field_type }) => ({
      data_input_type,
      data_field_type,
    })
  );

  CustomFieldsTypes.bulkCreate(customFieldsData)
    .then((data) => {
      res.status(200).json({ success: true, data });
    })
    .catch((err) => {
      next(err);
    });
};
