const mongoose = require('mongoose');
const { DEFAULT_CURRENCY_CODE } = require('../../config/platformDefaults');

const getModel = (name, models = {}) => models[name] || mongoose.model(name);

const nextNumber = async (Model, tenantId) => {
  const count = await Model.countDocuments(tenantId ? { tenant: tenantId } : {});
  return count + 1;
};

const loadOfferQuery = (Offer, offerId, tenantId) =>
  Offer.findOne({
    _id: offerId,
    removed: false,
    ...(tenantId ? { tenant: tenantId } : {}),
  })
    .populate('contact')
    .populate('lead')
    .populate('deal');

const getPublishedPublicForm = async ({ slug, models = {} }) => {
  const PublicForm = getModel('PublicForm', models);
  const form = await PublicForm.findOne({
    slug,
    status: 'published',
    removed: false,
  }).exec();

  if (!form) {
    const error = new Error('Public form not found');
    error.status = 404;
    throw error;
  }

  return {
    _id: form._id,
    tenant: form.tenant,
    name: form.name,
    slug: form.slug,
    description: form.description,
    targetEntity: form.targetEntity,
    fields: form.fields || [],
    successMessage: form.successMessage,
    status: form.status,
  };
};

const getPublishedFormDefinition = async ({ slug, models = {} }) => {
  const FormDefinition = getModel('FormDefinition', models);
  const formDefinition = await FormDefinition.findOne({
    slug,
    type: 'public',
    status: 'published',
    removed: false,
  }).exec();

  if (!formDefinition) {
    const error = new Error('Form definition not found');
    error.status = 404;
    throw error;
  }

  return {
    _id: formDefinition._id,
    tenant: formDefinition.tenant,
    name: formDefinition.name,
    slug: formDefinition.slug,
    description: formDefinition.description,
    targetEntity: formDefinition.targetEntity,
    fields: formDefinition.fields || [],
    successMessage: formDefinition.successMessage,
    status: formDefinition.status,
    type: formDefinition.type,
  };
};

const normalizeSubmissionPayload = (payload = {}) =>
  Object.entries(payload || {}).reduce((acc, [key, value]) => {
    if (value !== undefined && value !== null && value !== '') {
      acc[key] = value;
    }
    return acc;
  }, {});

const validateSubmissionFields = (fields = [], payload = {}) => {
  for (const field of fields || []) {
    const fieldKey = typeof field === 'string' ? field : field?.key;
    const fieldLabel = typeof field === 'string' ? field : field?.label || field?.key;
    const required = typeof field === 'string' ? ['firstName', 'name', 'email'].includes(field) : field?.required === true;

    if (required && (payload[fieldKey] === undefined || payload[fieldKey] === null || payload[fieldKey] === '')) {
      const error = new Error(`${fieldLabel} is required`);
      error.status = 400;
      throw error;
    }
  }
};

const deriveContactIdentity = (payload = {}) => {
  const fullName = payload.fullName || payload.name || '';
  const inferredParts = String(fullName).trim().split(/\s+/).filter(Boolean);
  const firstName = payload.firstName || inferredParts[0] || payload.email || 'New';
  const lastName = payload.lastName || inferredParts.slice(1).join(' ') || undefined;
  const name = payload.name || payload.fullName || [firstName, lastName].filter(Boolean).join(' ');

  return {
    firstName,
    lastName,
    name,
    email: payload.email,
    phone: payload.phone,
    whatsapp: payload.whatsapp,
  };
};

const applyMissingValues = (record, values = {}) => {
  let changed = false;

  Object.entries(values).forEach(([key, value]) => {
    if (value === undefined || value === null || value === '') return;
    if (record[key] === undefined || record[key] === null || record[key] === '') {
      record[key] = value;
      changed = true;
    }
  });

  return changed;
};

const safeFindOne = async (Model, query, options = {}) => {
  if (!Model || typeof Model.findOne !== 'function') return null;

  const request = Model.findOne(query);
  if (options.sort && request && typeof request.sort === 'function') {
    return request.sort(options.sort).exec();
  }
  if (request && typeof request.exec === 'function') {
    return request.exec();
  }
  return request || null;
};

const createTargetRecordFromSubmission = async ({
  targetEntity,
  payload = {},
  tenantId,
  actorId,
  source = 'form_submission',
  title = 'New submission',
  models = {},
}) => {
  const Contact = getModel('Contact', models);
  const Lead = getModel('Lead', models);
  const Client = getModel('Client', models);

  const contactIdentity = deriveContactIdentity(payload);
  const lifecycleStage = targetEntity === 'client' ? 'customer' : 'lead';
  let contact = null;

  if (contactIdentity.email) {
    contact = await safeFindOne(Contact, {
      tenant: tenantId,
      email: contactIdentity.email,
      removed: false,
    });
  }

  if (!contact && contactIdentity.phone) {
    contact = await safeFindOne(Contact, {
      tenant: tenantId,
      phone: contactIdentity.phone,
      removed: false,
    });
  }

  if (contact) {
    const changed = applyMissingValues(contact, {
      ...contactIdentity,
      lifecycleStage: contact.lifecycleStage === 'customer' ? 'customer' : lifecycleStage,
      assignedTo: contact.assignedTo || actorId,
    });
    if (changed) {
      await contact.save();
    }
  } else {
    contact = await Contact.create({
      tenant: tenantId,
      ...contactIdentity,
      lifecycleStage,
      createdBy: actorId,
      assignedTo: actorId,
    });
  }

  if (targetEntity === 'contact') {
    return { contact, record: contact };
  }

  if (targetEntity === 'client') {
    let client = null;

    if (contact.email) {
      client = await safeFindOne(Client, {
        tenant: tenantId,
        email: contact.email,
        removed: false,
      });
    }

    if (!client && contact.phone) {
      client = await safeFindOne(Client, {
        tenant: tenantId,
        phone: contact.phone,
        removed: false,
      });
    }

    if (client) {
      const changed = applyMissingValues(client, {
        name: contact.name || [contact.firstName, contact.lastName].filter(Boolean).join(' '),
        email: contact.email,
        phone: contact.phone,
        lifecycleStage: 'customer',
        assignedTo: client.assignedTo || actorId,
      });
      if (changed) {
        await client.save();
      }
    } else {
      client = await Client.create({
        tenant: tenantId,
        name: contact.name || [contact.firstName, contact.lastName].filter(Boolean).join(' '),
        email: contact.email,
        phone: contact.phone,
        lifecycleStage: 'customer',
        createdBy: actorId,
        assignedTo: actorId,
      });
    }
    return { contact, record: client };
  }

  let lead = await safeFindOne(
    Lead,
    {
      tenant: tenantId,
      contact: contact._id,
      removed: false,
      ...(source ? { source } : {}),
    },
    { sort: { created: -1 } }
  );

  if (lead) {
    const changed = applyMissingValues(lead, {
      title: payload.title || payload.subject || title,
      source,
      assignedTo: lead.assignedTo || actorId,
    });
    if (changed) {
      await lead.save();
    }
  } else {
    lead = await Lead.create({
      tenant: tenantId,
      title: payload.title || payload.subject || title,
      contact: contact._id,
      source,
      status: 'new',
      createdBy: actorId,
      assignedTo: actorId,
    });
  }

  return { contact, record: lead };
};

const computeInvoicePaymentStatus = ({ total = 0, discount = 0, credit = 0 }) => {
  const outstanding = Number(total || 0) - Number(discount || 0);
  if (outstanding <= 0 || Number(credit || 0) >= outstanding) return 'paid';
  if (Number(credit || 0) > 0) return 'partially';
  return 'unpaid';
};

const convertOfferToInvoice = async ({
  offerId,
  tenantId,
  actorId,
  models = {},
  publishEvent = async () => null,
}) => {
  const Offer = getModel('Offer', models);
  const Client = getModel('Client', models);
  const Invoice = getModel('Invoice', models);

  const offer = await loadOfferQuery(Offer, offerId, tenantId).exec();
  if (!offer) {
    const error = new Error('Offer not found');
    error.status = 404;
    throw error;
  }

  let client = null;
  const contact = offer.contact || offer.lead?.contact || null;
  if (contact?.email) {
    client = await Client.findOne({
      tenant: tenantId,
      email: contact.email,
      removed: false,
    }).exec();
  }

  if (!client) {
    client = await Client.create({
      tenant: tenantId,
      name: contact?.name || offer.title,
      email: contact?.email,
      phone: contact?.phone,
      lifecycleStage: 'customer',
      createdBy: actorId,
      assignedTo: actorId,
    });
  }

  const total = offer.value?.amount || offer.total || 0;
  const invoice = await Invoice.create({
    tenant: tenantId,
    createdBy: actorId,
    assignedTo: actorId,
    number: await nextNumber(Invoice, tenantId),
    year: new Date().getFullYear(),
    date: new Date(),
    expiredDate: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000),
    client: client._id,
    contact: contact?._id,
    deal: offer.deal?._id,
    converted: {
      from: 'offer',
      offer: offer._id,
      quote: undefined,
    },
    items:
      offer.items?.length > 0
        ? offer.items
        : [
            {
              itemName: offer.title,
              quantity: 1,
              price: total,
              total,
            },
          ],
    subTotal: total,
    total,
    currency: offer.value?.currency || DEFAULT_CURRENCY_CODE,
    notes: offer.notes,
    status: 'draft',
    paymentStatus: 'unpaid',
  });

  offer.status = 'converted';
  if (typeof offer.save === 'function') {
    await offer.save();
  }

  await publishEvent({
    tenant: tenantId,
    type: 'sales.offer.converted',
    sourceModule: 'sales',
    entity: 'offer',
    entityId: offer._id,
    actor: actorId,
    payload: { offer, invoice, client },
  });

  return { offer, invoice, client };
};

const STATUS_RULES = {
  order: {
    modelName: 'Order',
    eventType: 'inventory.order.status_changed',
    allowed: ['draft', 'confirmed', 'processing', 'delivered', 'returned', 'refunded', 'cancelled'],
  },
  purchaseorder: {
    modelName: 'PurchaseOrder',
    eventType: 'vendors.purchaseorder.status_changed',
    allowed: ['draft', 'pending_approval', 'approved', 'processing', 'received', 'returned', 'refunded', 'cancelled'],
  },
};

const transitionEntityStatus = async ({
  entityName,
  entityId,
  status,
  tenantId,
  actorId,
  models = {},
  publishEvent = async () => null,
}) => {
  const rule = STATUS_RULES[String(entityName || '').toLowerCase()];
  if (!rule) {
    const error = new Error('Unsupported workflow status entity');
    error.status = 400;
    throw error;
  }
  if (!rule.allowed.includes(status)) {
    const error = new Error('Unsupported status transition');
    error.status = 400;
    throw error;
  }

  const Model = getModel(rule.modelName, models);
  const record = await Model.findOne({
    _id: entityId,
    removed: false,
    ...(tenantId ? { tenant: tenantId } : {}),
  }).exec();

  if (!record) {
    const error = new Error('Record not found');
    error.status = 404;
    throw error;
  }

  record.status = status;
  if (actorId && record.assignedTo == null) {
    record.assignedTo = actorId;
  }
  await record.save();

  await publishEvent({
    tenant: tenantId,
    type: rule.eventType,
    sourceModule: rule.modelName === 'Order' ? 'inventory' : 'vendors',
    entity: entityName,
    entityId: record._id,
    actor: actorId,
    payload: { status, record },
  });

  return { record };
};

const submitPublicForm = async ({
  slug,
  payload = {},
  tenantId,
  actorId,
  models = {},
  providers = {},
  publishEvent = async () => null,
}) => {
  const PublicForm = getModel('PublicForm', models);

  const form = await PublicForm.findOne({
    slug,
    removed: false,
    ...(tenantId ? { tenant: tenantId } : {}),
  }).exec();

  if (!form) {
    const error = new Error('Public form not found');
    error.status = 404;
    throw error;
  }

  const resolvedTenantId = tenantId || form.tenant;
  const normalizedPayload = normalizeSubmissionPayload(payload);
  validateSubmissionFields(form.fields || [], normalizedPayload);
  const { contact, record } = await createTargetRecordFromSubmission({
    targetEntity: form.targetEntity,
    payload: normalizedPayload,
    tenantId: resolvedTenantId,
    actorId,
    source: 'public_form',
    title: `Lead from ${form.name}`,
    models,
  });

  let autoReply = null;
  if (form.autoReplyEnabled && contact.email && providers.resend?.sendEmail) {
    autoReply = await providers.resend.sendEmail({
      to: contact.email,
      subject: form.autoReplySubject || `Thanks for contacting ${form.name}`,
      html: `<p>${form.autoReplyBody || 'Thanks for your submission.'}</p>`,
    });
  }

  await publishEvent({
    tenant: resolvedTenantId,
    type: 'platform.publicform.submitted',
    sourceModule: 'platform',
    entity: 'publicform',
    entityId: form._id,
    actor: actorId,
    payload: { form, contact, record },
  });

  return { form, contact, record, autoReply };
};

const submitFormDefinition = async ({
  formDefinitionId,
  slug,
  payload = {},
  tenantId,
  actorId,
  models = {},
  providers = {},
  publishEvent = async () => null,
  publicOnly = false,
}) => {
  const FormDefinition = getModel('FormDefinition', models);
  const FormSubmission = getModel('FormSubmission', models);

  const formDefinition = await FormDefinition.findOne({
    ...(formDefinitionId ? { _id: formDefinitionId } : { slug }),
    removed: false,
    ...(tenantId ? { tenant: tenantId } : {}),
    ...(publicOnly ? { type: 'public', status: 'published' } : {}),
  }).exec();

  if (!formDefinition) {
    const error = new Error('Form definition not found');
    error.status = 404;
    throw error;
  }

  const resolvedTenantId = tenantId || formDefinition.tenant;
  const normalizedPayload = normalizeSubmissionPayload(payload);
  validateSubmissionFields(formDefinition.fields || [], normalizedPayload);

  const submission = await FormSubmission.create({
    tenant: resolvedTenantId,
    createdBy: actorId,
    assignedTo: actorId,
    formDefinition: formDefinition._id,
    targetEntity: formDefinition.targetEntity,
    payload: normalizedPayload,
    source: formDefinition.type,
  });

  const { contact, record } = await createTargetRecordFromSubmission({
    targetEntity: formDefinition.targetEntity,
    payload: normalizedPayload,
    tenantId: resolvedTenantId,
    actorId,
    source: formDefinition.type === 'public' ? 'form_builder_public' : 'form_builder',
    title: `Lead from ${formDefinition.name}`,
    models,
  });

  submission.relatedRecordId = record?._id;
  await submission.save();

  let autoReply = null;
  if (formDefinition.autoReplyEnabled && contact?.email && providers.resend?.sendEmail) {
    autoReply = await providers.resend.sendEmail({
      to: contact.email,
      subject: formDefinition.autoReplySubject || `Thanks for contacting ${formDefinition.name}`,
      html: `<p>${formDefinition.autoReplyBody || 'Thanks for your submission.'}</p>`,
    });
  }

  await publishEvent({
    tenant: resolvedTenantId,
    type: 'platform.formdefinition.submitted',
    sourceModule: 'platform',
    entity: 'formdefinition',
    entityId: formDefinition._id,
    actor: actorId,
    payload: { formDefinition, submission, contact, record },
  });

  return { formDefinition, submission, contact, record, autoReply };
};

const submitLoadCalculatorLead = async ({
  payload = {},
  tenantId,
  actorId,
  models = {},
  providers = {},
  publishEvent = async () => null,
}) => {
  const Activity = getModel('Activity', models);
  const resolvedTenantId = tenantId;
  const normalizedPayload = normalizeSubmissionPayload(payload);

  if (!normalizedPayload.name && !normalizedPayload.firstName) {
    const error = new Error('Name is required');
    error.status = 400;
    throw error;
  }

  if (!normalizedPayload.email) {
    const error = new Error('Email is required');
    error.status = 400;
    throw error;
  }

  const appliances = Array.isArray(normalizedPayload.appliances) ? normalizedPayload.appliances : [];
  const totalPowerWatts = Number(normalizedPayload.totalPowerWatts || 0);
  const totalEnergyWh = Number(normalizedPayload.totalEnergyWh || 0);
  const recommendedInverterKva = Number(normalizedPayload.recommendedInverterKva || 0);
  const attribution = {
    utmSource: normalizedPayload.utmSource || normalizedPayload.utm_source,
    utmMedium: normalizedPayload.utmMedium || normalizedPayload.utm_medium,
    utmCampaign: normalizedPayload.utmCampaign || normalizedPayload.utm_campaign,
    utmTerm: normalizedPayload.utmTerm || normalizedPayload.utm_term,
    utmContent: normalizedPayload.utmContent || normalizedPayload.utm_content,
    referrer: normalizedPayload.referrer,
    landingPage: normalizedPayload.landingPage,
  };

  const { contact, record } = await createTargetRecordFromSubmission({
    targetEntity: 'lead',
    payload: normalizedPayload,
    tenantId: resolvedTenantId,
    actorId,
    source: 'load_calculator',
    title: normalizedPayload.projectType
      ? `Load Calculator - ${normalizedPayload.projectType}`
      : 'Load Calculator Lead',
    models,
  });

  const calculatorSummary = [
    `Project type: ${normalizedPayload.projectType || 'Not specified'}`,
    `Installation location: ${normalizedPayload.location || 'Not specified'}`,
    `Total power: ${totalPowerWatts} W`,
    `Daily energy: ${totalEnergyWh} Wh/day`,
    `Recommended inverter: ${recommendedInverterKva} kVA`,
    `Website source: ${attribution.utmSource || normalizedPayload.source || 'Direct / not provided'}`,
    `Campaign: ${attribution.utmCampaign || 'Not provided'}`,
    `Medium: ${attribution.utmMedium || 'Not provided'}`,
    `Referrer: ${attribution.referrer || 'Not provided'}`,
    `Landing page: ${attribution.landingPage || 'Not provided'}`,
    '',
    'Appliances:',
    ...(appliances.length
      ? appliances.map(
          (item) =>
            `- ${item.name || 'Appliance'} | ${item.watts || 0}W | qty ${item.quantity || 0} | ${item.hoursPerDay || 0} hrs/day | ${item.totalWh || 0} Wh/day`
        )
      : ['- No appliances provided']),
  ].join('\n');

  const activity = await Activity.create({
    tenant: resolvedTenantId,
    createdBy: actorId,
    assignedTo: actorId,
    type: 'note',
    subject: 'Solar load calculation submitted',
    body: calculatorSummary,
    contact: contact._id,
    relatedTo: {
      entityType: 'lead',
      entityId: record._id,
    },
  });

  let autoReply = null;
  if (normalizedPayload.email && providers.resend?.sendEmail) {
    autoReply = await providers.resend.sendEmail({
      to: normalizedPayload.email,
      subject: 'Your load calculation request has been received',
      html: `<p>Thanks for using our load calculator.</p><p>Total power: ${totalPowerWatts} W</p><p>Daily energy: ${totalEnergyWh} Wh/day</p><p>Estimated inverter size: ${recommendedInverterKva} kVA</p>`,
    });
  }

  await publishEvent({
    tenant: resolvedTenantId,
    type: 'crm.load_calculator.submitted',
    sourceModule: 'crm',
    entity: 'lead',
    entityId: record._id,
    actor: actorId,
    payload: { contact, lead: record, activity, calculator: normalizedPayload, attribution },
  });

  return { contact, lead: record, activity, autoReply };
};

const recordInvoicePayment = async ({
  invoiceId,
  paymentInput = {},
  tenantId,
  actorId,
  models = {},
  publishEvent = async () => null,
}) => {
  const Invoice = getModel('Invoice', models);
  const Payment = getModel('Payment', models);

  const invoice = await Invoice.findOne({
    _id: invoiceId,
    removed: false,
    ...(tenantId ? { tenant: tenantId } : {}),
  }).exec();

  if (!invoice) {
    const error = new Error('Invoice not found');
    error.status = 404;
    throw error;
  }

  const amount = Number(paymentInput.amount || 0);
  if (amount <= 0) {
    const error = new Error("The Minimum Amount couldn't be 0");
    error.status = 400;
    throw error;
  }

  const outstanding = Number(invoice.total || 0) - Number(invoice.discount || 0) - Number(invoice.credit || 0);
  if (amount > outstanding) {
    const error = new Error(`The Max Amount you can add is ${outstanding}`);
    error.status = 400;
    throw error;
  }

  const payment = await Payment.create({
    tenant: tenantId || invoice.tenant,
    createdBy: actorId,
    assignedTo: actorId,
    number: await nextNumber(Payment, tenantId || invoice.tenant),
    client: invoice.client?._id || invoice.client,
    invoice: invoice._id,
    paymentMode: paymentInput.paymentMode,
    amount,
    currency: paymentInput.currency || invoice.currency || DEFAULT_CURRENCY_CODE,
    ref: paymentInput.ref,
    description: paymentInput.description,
    date: paymentInput.date ? new Date(paymentInput.date) : new Date(),
    reconciled: Boolean(paymentInput.reconciled),
    reconciledAt: paymentInput.reconciled ? new Date() : undefined,
  });

  invoice.credit = Number(invoice.credit || 0) + amount;
  invoice.paymentStatus = computeInvoicePaymentStatus(invoice);
  invoice.payment = [...(invoice.payment || []), payment._id];
  if (typeof invoice.save === 'function') {
    await invoice.save();
  }

  await publishEvent({
    tenant: tenantId || invoice.tenant,
    type: 'finance.invoice.payment_recorded',
    sourceModule: 'finance',
    entity: 'invoice',
    entityId: invoice._id,
    actor: actorId,
    payload: { invoice, payment },
  });

  return { invoice, payment };
};

const reconcilePaymentRecord = async ({
  paymentId,
  tenantId,
  actorId,
  models = {},
  publishEvent = async () => null,
}) => {
  const Payment = getModel('Payment', models);
  const payment = await Payment.findOne({
    _id: paymentId,
    removed: false,
    ...(tenantId ? { tenant: tenantId } : {}),
  }).exec();

  if (!payment) {
    const error = new Error('Payment not found');
    error.status = 404;
    throw error;
  }

  payment.reconciled = true;
  payment.reconciledAt = new Date();
  if (typeof payment.save === 'function') {
    await payment.save();
  }

  await publishEvent({
    tenant: tenantId || payment.tenant,
    type: 'finance.payment.reconciled',
    sourceModule: 'finance',
    entity: 'payment',
    entityId: payment._id,
    actor: actorId,
    payload: { payment },
  });

  return { payment };
};

const countByStatus = async (Model, tenantId) => {
  const result = await Model.aggregate([
    {
      $match: {
        removed: false,
        ...(tenantId ? { tenant: tenantId } : {}),
      },
    },
    {
      $group: {
        _id: '$status',
        count: { $sum: 1 },
      },
    },
    {
      $sort: { _id: 1 },
    },
  ]);

  return result.map((item) => ({ status: item._id, count: item.count }));
};

const buildEnterpriseOverviewReport = async ({ tenantId, models = {} }) => {
  const Invoice = getModel('Invoice', models);
  const Payment = getModel('Payment', models);
  const Order = getModel('Order', models);
  const PurchaseOrder = getModel('PurchaseOrder', models);
  const AutomationEvent = getModel('AutomationEvent', models);
  const PublicForm = getModel('PublicForm', models);

  const [invoiceRollup = {}, paymentRollup = {}, orderStatuses, purchaseStatuses, publicFormSubmissions, publishedForms, convertedOffers, paymentsRecorded, reconciledPayments] =
    await Promise.all([
      Invoice.aggregate([
        {
          $match: {
            removed: false,
            ...(tenantId ? { tenant: tenantId } : {}),
          },
        },
        {
          $group: {
            _id: null,
            count: { $sum: 1 },
            total: { $sum: '$total' },
            outstanding: { $sum: { $subtract: ['$total', '$credit'] } },
            paidCount: {
              $sum: { $cond: [{ $eq: ['$paymentStatus', 'paid'] }, 1, 0] },
            },
            partialCount: {
              $sum: { $cond: [{ $eq: ['$paymentStatus', 'partially'] }, 1, 0] },
            },
            unpaidCount: {
              $sum: { $cond: [{ $eq: ['$paymentStatus', 'unpaid'] }, 1, 0] },
            },
          },
        },
        {
          $project: {
            _id: 0,
            count: 1,
            total: 1,
            outstanding: 1,
            paidCount: 1,
            partialCount: 1,
            unpaidCount: 1,
          },
        },
      ]).then((rows) => rows[0] || {}),
      Payment.aggregate([
        {
          $match: {
            removed: false,
            ...(tenantId ? { tenant: tenantId } : {}),
          },
        },
        {
          $group: {
            _id: null,
            count: { $sum: 1 },
            total: { $sum: '$amount' },
            reconciledCount: {
              $sum: { $cond: ['$reconciled', 1, 0] },
            },
            unreconciledCount: {
              $sum: { $cond: ['$reconciled', 0, 1] },
            },
          },
        },
        {
          $project: {
            _id: 0,
            count: 1,
            total: 1,
            reconciledCount: 1,
            unreconciledCount: 1,
          },
        },
      ]).then((rows) => rows[0] || {}),
      countByStatus(Order, tenantId),
      countByStatus(PurchaseOrder, tenantId),
      AutomationEvent.countDocuments({
        removed: false,
        ...(tenantId ? { tenant: tenantId } : {}),
        type: 'platform.publicform.submitted',
      }),
      PublicForm.countDocuments({
        removed: false,
        ...(tenantId ? { tenant: tenantId } : {}),
        status: 'published',
      }),
      AutomationEvent.countDocuments({
        removed: false,
        ...(tenantId ? { tenant: tenantId } : {}),
        type: 'sales.offer.converted',
      }),
      AutomationEvent.countDocuments({
        removed: false,
        ...(tenantId ? { tenant: tenantId } : {}),
        type: 'finance.invoice.payment_recorded',
      }),
      AutomationEvent.countDocuments({
        removed: false,
        ...(tenantId ? { tenant: tenantId } : {}),
        type: 'finance.payment.reconciled',
      }),
    ]);

  return {
    finance: {
      invoices: {
        count: invoiceRollup.count || 0,
        total: invoiceRollup.total || 0,
        outstanding: invoiceRollup.outstanding || 0,
        paidCount: invoiceRollup.paidCount || 0,
        partialCount: invoiceRollup.partialCount || 0,
        unpaidCount: invoiceRollup.unpaidCount || 0,
      },
      payments: {
        count: paymentRollup.count || 0,
        total: paymentRollup.total || 0,
        reconciledCount: paymentRollup.reconciledCount || 0,
        unreconciledCount: paymentRollup.unreconciledCount || 0,
      },
    },
    operations: {
      orders: {
        total: orderStatuses.reduce((sum, item) => sum + item.count, 0),
        statusCounts: orderStatuses,
      },
      purchases: {
        total: purchaseStatuses.reduce((sum, item) => sum + item.count, 0),
        statusCounts: purchaseStatuses,
      },
    },
    conversions: {
      publicFormSubmissions,
      publishedForms,
      convertedOffers,
      paymentsRecorded,
      reconciledPayments,
    },
  };
};

module.exports = {
  convertOfferToInvoice,
  transitionEntityStatus,
  submitPublicForm,
  submitFormDefinition,
  submitLoadCalculatorLead,
  getPublishedPublicForm,
  getPublishedFormDefinition,
  recordInvoicePayment,
  reconcilePaymentRecord,
  buildEnterpriseOverviewReport,
};
