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

const load = async (req, res) => {
  try {
    const Tenant = mongoose.model('Tenant');
    const tenant = await Tenant.findOne({
      slug: String(req.params.tenantSlug || '').toLowerCase(),
      removed: false,
      enabled: true,
    }).lean();

    if (!tenant) {
      return res.status(404).json({
        success: false,
        result: null,
        message: 'Tenant not found',
      });
    }

    return res.status(200).json({
      success: true,
      result: {
        tenant: {
          _id: tenant._id,
          name: tenant.name,
          slug: tenant.slug,
        },
      },
      message: 'Load calculator configuration loaded',
    });
  } catch (error) {
    return res.status(500).json({
      success: false,
      result: null,
      message: error.message || 'Unable to load calculator configuration',
    });
  }
};

const submit = async (req, res) => {
  try {
    const Tenant = mongoose.model('Tenant');
    const tenant = await Tenant.findOne({
      slug: String(req.params.tenantSlug || '').toLowerCase(),
      removed: false,
      enabled: true,
    }).lean();

    if (!tenant) {
      return res.status(404).json({
        success: false,
        result: null,
        message: 'Tenant not found',
      });
    }

    const result = await submitLoadCalculatorLead({
      tenantId: tenant._id,
      payload: req.body || {},
      providers: await createProviderRegistryForTenant({ tenantId: tenant._id }),
      publishEvent: publishAutomationEvent,
    });

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

module.exports = {
  load,
  submit,
};
