const mongoose = require('mongoose');
const { createProviderRegistryForTenant } = require('@/services/integrations/providerRegistry');
const { publishAutomationEvent } = require('@/services/automation/eventBus');
const { submitFormDefinition } = require('@/services/platform/enterpriseWorkflows');

const normalizeFields = (fields = []) =>
  (Array.isArray(fields) ? fields : []).map((field, index) => ({
    key: field.key || `field_${index + 1}`,
    label: field.label || field.key || `Field ${index + 1}`,
    type: field.type || 'text',
    required: field.required === true,
    options: Array.isArray(field.options) ? field.options : [],
    placeholder: field.placeholder || '',
  }));

const definitions = async (req, res) => {
  const FormDefinition = mongoose.model('FormDefinition');
  const result = await FormDefinition.find({ tenant: req.tenantId, removed: false }).sort({ created: -1 }).lean();
  return res.status(200).json({ success: true, result, message: 'Form definitions loaded' });
};

const saveDefinition = async (req, res) => {
  const FormDefinition = mongoose.model('FormDefinition');
  const FormFieldDefinition = mongoose.model('FormFieldDefinition');

  const result = await FormDefinition.create({
    tenant: req.tenantId,
    createdBy: req.admin?._id,
    assignedTo: req.admin?._id,
    name: req.body?.name,
    slug: req.body?.slug,
    type: req.body?.type || 'internal',
    targetEntity: req.body?.targetEntity || 'lead',
    description: req.body?.description,
    fields: normalizeFields(req.body?.fields),
    successMessage: req.body?.successMessage,
    autoReplyEnabled: req.body?.autoReplyEnabled === true,
    autoReplySubject: req.body?.autoReplySubject,
    autoReplyBody: req.body?.autoReplyBody,
    status: req.body?.status || 'draft',
  });

  await FormFieldDefinition.insertMany(
    normalizeFields(req.body?.fields).map((field) => ({
      tenant: req.tenantId,
      createdBy: req.admin?._id,
      assignedTo: req.admin?._id,
      formDefinition: result._id,
      ...field,
    }))
  );

  return res.status(201).json({ success: true, result, message: 'Form definition created' });
};

const updateDefinition = async (req, res) => {
  const FormDefinition = mongoose.model('FormDefinition');
  const FormFieldDefinition = mongoose.model('FormFieldDefinition');
  const normalizedFields = normalizeFields(req.body?.fields);

  const result = await FormDefinition.findOneAndUpdate(
    { _id: req.params.id, tenant: req.tenantId, removed: false },
    {
      $set: {
        name: req.body?.name,
        slug: req.body?.slug,
        type: req.body?.type || 'internal',
        targetEntity: req.body?.targetEntity || 'lead',
        description: req.body?.description,
        fields: normalizedFields,
        successMessage: req.body?.successMessage,
        autoReplyEnabled: req.body?.autoReplyEnabled === true,
        autoReplySubject: req.body?.autoReplySubject,
        autoReplyBody: req.body?.autoReplyBody,
        status: req.body?.status || 'draft',
      },
    },
    { new: true }
  );

  await FormFieldDefinition.deleteMany({ tenant: req.tenantId, formDefinition: req.params.id });
  if (normalizedFields.length) {
    await FormFieldDefinition.insertMany(
      normalizedFields.map((field) => ({
        tenant: req.tenantId,
        createdBy: req.admin?._id,
        assignedTo: req.admin?._id,
        formDefinition: req.params.id,
        ...field,
      }))
    );
  }

  return res.status(200).json({ success: true, result, message: 'Form definition updated' });
};

const submit = async (req, res) => {
  try {
    const result = await submitFormDefinition({
      formDefinitionId: req.params.id,
      tenantId: req.tenantId,
      actorId: req.admin?._id,
      payload: req.body?.payload || req.body || {},
      providers: await createProviderRegistryForTenant({ tenantId: req.tenantId }),
      publishEvent: publishAutomationEvent,
    });

    return res.status(201).json({ success: true, result, message: 'Form submitted' });
  } catch (error) {
    return res.status(error.status || 500).json({
      success: false,
      result: null,
      message: error.message || 'Unable to submit form',
    });
  }
};

const submissions = async (req, res) => {
  const FormSubmission = mongoose.model('FormSubmission');
  const result = await FormSubmission.find({ tenant: req.tenantId, removed: false })
    .sort({ submittedAt: -1, created: -1 })
    .limit(Number(req.query?.items || 100))
    .lean();
  return res.status(200).json({ success: true, result, message: 'Form submissions loaded' });
};

module.exports = {
  definitions,
  saveDefinition,
  updateDefinition,
  submit,
  submissions,
};
