const mongoose = require('mongoose');
const { processDueAutomationJobs } = require('@/services/automation/runner');
const { buildAutomationWorkspaceSummary } = require('@/services/platform/growthWorkspaces');

const runDue = async (req, res) => {
  const limit = Number(req.body?.limit || req.query?.limit || 10);
  const results = await processDueAutomationJobs({ limit });

  return res.status(200).json({
    success: true,
    result: {
      processed: results.length,
      results: results.map((item) => ({
        processed: item.processed,
        job: item.job?._id,
        run: item.run?._id,
        status: item.run?.status || item.job?.status,
        error: item.error?.message,
      })),
    },
    message: 'Automation jobs processed',
  });
};

const runHistory = async (req, res) => {
  const limit = Number(req.query.limit || 20);
  const runs = await mongoose
    .model('AutomationRun')
    .find({
      removed: false,
      ...(req.tenantId ? { tenant: req.tenantId } : {}),
    })
    .sort({ created: -1 })
    .limit(limit)
    .populate()
    .exec();

  return res.status(200).json({
    success: true,
    result: runs,
    message: 'Automation run history loaded',
  });
};

const calendar = async (req, res) => {
  const from = req.query.from ? new Date(req.query.from) : new Date(Date.now() - 7 * 86400000);
  const to = req.query.to ? new Date(req.query.to) : new Date(Date.now() + 60 * 86400000);
  const [rules, jobs] = await Promise.all([
    mongoose.model('AutomationRule').find({ tenant: req.tenantId, removed: false, 'trigger.type': 'time' }).lean(),
    mongoose.model('Job').find({ tenant: req.tenantId, removed: false, type: 'automation.run', runAfter: { $gte: from, $lte: to } }).lean(),
  ]);
  const result = [
    ...rules.map((rule) => ({
      id: String(rule._id),
      type: 'automation_job',
      title: rule.name,
      start: rule.trigger?.nextRunAt || rule.updated,
      end: rule.trigger?.nextRunAt || rule.updated,
      status: rule.enabled === false ? 'paused' : 'scheduled',
      owner: req.admin?._id,
      riskLevel: 'medium',
      linkedEntity: { entityType: 'AutomationRule', entityId: rule._id },
      actionUrl: '/automations/calendar',
    })),
    ...jobs.map((job) => ({
      id: String(job._id),
      type: 'automation_job',
      title: 'Queued automation job',
      start: job.runAfter,
      end: job.runAfter,
      status: job.status,
      owner: req.admin?._id,
      riskLevel: job.status === 'failed' ? 'high' : 'low',
      linkedEntity: { entityType: 'Job', entityId: job._id },
      actionUrl: '/automations/calendar',
    })),
  ];
  return res.status(200).json({ success: true, result, message: 'Automation calendar loaded' });
};

const retryRun = async (req, res) => {
  const existing = await mongoose.model('AutomationRun').findOne({ _id: req.params.id, tenant: req.tenantId, removed: false });
  if (!existing) return res.status(404).json({ success: false, message: 'Automation run not found' });
  const result = await mongoose.model('Job').create({
    tenant: req.tenantId,
    createdBy: req.admin?._id,
    type: 'automation.run',
    payload: { rule: existing.rule, event: existing.event, retryOf: existing._id },
    status: 'queued',
  });
  return res.status(200).json({ success: true, result, message: 'Automation retry queued' });
};

const operationsSummary = async (req, res) =>
  res.status(200).json({
    success: true,
    result: await buildAutomationWorkspaceSummary({ tenantId: req.tenantId }),
    message: 'Automation operations summary loaded',
  });

module.exports = { runDue, runHistory, calendar, retryRun, operationsSummary };
