const express = require('express');

const DEFAULT_MOCK_API_PORT = Number(process.env.MOCK_API_PORT || 6524);

function getOperationResponse(operation, body) {
  const callerNumber = body?.callerNumber || '22700000000';
  const now = new Date().toISOString();

  switch (operation) {
    case 'fraud-check':
      return {
        fraud: false,
        riskScore: 8,
        reason: 'Caller not present in fraud or blacklist table',
      };
    case 'rmn-nrmn':
      return {
        callerType: 'RMN',
        linkedAccounts: [
          { hbbNumber: 'HBB-NE-000123', status: 'ACTIVE' },
          { hbbNumber: 'HBB-NE-000124', status: 'ACTIVE' },
        ],
      };
    case 'application-transfer-check':
      return {
        authorized: true,
        transferRequired: false,
      };
    case 'language-selection':
      return {
        preferredLanguage: 'french',
        available: ['french', 'hausa', 'zarma'],
      };
    case 'hbb-callers':
      return {
        hasMultipleAccounts: true,
        accountCount: 2,
      };
    case 'enter-hbb-number':
      return {
        valid: true,
        normalizedNumber: 'HBB-NE-000123',
      };
    case 'select-hbb-number':
      return {
        selectedAccount: 'HBB-NE-000123',
      };
    case 'buy-bundles':
      return {
        offers: [
          { id: 'BUNDLE-7D-5GB', price: 5000, currency: 'XOF' },
          { id: 'BUNDLE-30D-20GB', price: 15000, currency: 'XOF' },
        ],
      };
    case 'airtel-money-services':
      return {
        walletNumber: callerNumber,
        walletStatus: 'ACTIVE',
      };
    case 'check-balance':
      return {
        remainingDataMb: 920,
        expiryDate: '2026-03-31',
      };
    case 'open-ticket':
      return {
        ticketId: `TKT-${Date.now()}`,
        status: 'OPEN',
        slaHours: 24,
      };
    case 'billing-inquiry':
      return {
        outstandingAmount: 0,
        currency: 'XOF',
        lastInvoiceDate: '2026-02-28',
      };
    case 'connectivity-settings':
      return {
        signalLevel: 'GOOD',
        modemOnline: true,
        lastSeenAt: now,
      };
    case 'general-information':
      return {
        kbArticleId: 'HBB-FAQ-001',
        topic: 'Device restart and Wi-Fi troubleshooting',
      };
    case 'business-hours-check':
      return {
        isBusinessHours: true,
        timezone: 'Africa/Niamey',
      };
    case 'sms-gateway':
      return {
        sent: true,
        messageId: `SMS-${Date.now()}`,
      };
    default:
      return {
        handled: false,
        note: 'No dedicated mock response configured',
      };
  }
}

function buildSampleOperationEnvelope(operation, body = {}) {
  return {
    success: true,
    operation,
    timestamp: new Date().toISOString(),
    requestEcho: {
      workflowId: body?.workflowId || null,
      taskId: body?.taskId || null,
      nodeId: body?.nodeId || null,
    },
    data: getOperationResponse(operation, body),
  };
}

function startMockApiServer({ port = DEFAULT_MOCK_API_PORT, host = '127.0.0.1' } = {}) {
  const app = express();
  app.use(express.json({ limit: '1mb' }));

  app.get('/health', (_req, res) => {
    res.json({
      success: true,
      service: 'fresh-hbb-internal-mock-api',
      timestamp: new Date().toISOString(),
    });
  });

  app.post('/internal/:operation', (req, res) => {
    const operation = req.params.operation;
    res.json(buildSampleOperationEnvelope(operation, req.body));
  });

  const server = app.listen(port, host, () => {
    console.log(`Internal mock API listening on http://${host}:${port}`);
  });

  return server;
}

module.exports = {
  startMockApiServer,
  DEFAULT_MOCK_API_PORT,
  getOperationResponse,
  buildSampleOperationEnvelope,
};
