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

const getForm = async (req, res) => {
  try {
    const result = await getPublishedPublicForm({ slug: req.params.slug });
    return res.status(200).json({
      success: true,
      result,
      message: 'Public form loaded',
    });
  } catch (error) {
    return res.status(error.status || 500).json({
      success: false,
      result: null,
      message: error.message || 'Unable to load public form',
    });
  }
};

const submit = async (req, res) => {
  try {
    const form = await getPublishedPublicForm({ slug: req.params.slug });
    const result = await submitPublicForm({
      slug: req.params.slug,
      payload: req.body,
      providers: await createProviderRegistryForTenant({ tenantId: form?.tenant }),
      publishEvent: publishAutomationEvent,
    });

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

const getBuilderForm = async (req, res) => {
  try {
    const result = await getPublishedFormDefinition({ slug: req.params.slug });
    return res.status(200).json({
      success: true,
      result,
      message: 'Public form definition loaded',
    });
  } catch (error) {
    return res.status(error.status || 500).json({
      success: false,
      result: null,
      message: error.message || 'Unable to load public form definition',
    });
  }
};

const submitBuilderForm = async (req, res) => {
  try {
    const formDefinition = await getPublishedFormDefinition({ slug: req.params.slug });
    const result = await submitFormDefinition({
      slug: req.params.slug,
      payload: req.body,
      tenantId: formDefinition?.tenant,
      providers: await createProviderRegistryForTenant({ tenantId: formDefinition?.tenant }),
      publishEvent: publishAutomationEvent,
      publicOnly: true,
    });

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

module.exports = {
  getForm,
  submit,
  getBuilderForm,
  submitBuilderForm,
};
