const { getServiceSecret } = require('../config/serviceCredentials');
const { postRewardPayload } = require('../lib/rewardIntegrationClient');
const rewardPolicyService = require('./rewardPolicyService');

function buildSmokePayload(serviceName, payload = {}) {
  return {
    ...payload,
    idempotencyKey: `${serviceName}:HTTP_SMOKE:${Date.now()}:${Math.random().toString(16).slice(2)}`
  };
}

async function runDryRunSmoke({ baseUrl = 'http://127.0.0.1:4317', services = [] } = {}) {
  const manifest = rewardPolicyService.getIntegrationManifest();
  const requested = new Set((services || []).map((service) => String(service || '').trim().toUpperCase()).filter(Boolean));
  const sources = manifest.services.filter((source) => (
    source.serviceName !== 'AISFOR_CHAIN' &&
    (!requested.size || requested.has(source.serviceName))
  ));

  const rows = [];
  for (const source of sources) {
    const secret = getServiceSecret(source.serviceName);
    if (!secret) {
      rows.push({
        serviceName: source.serviceName,
        ok: false,
        status: 0,
        dryRunOk: false,
        authConfigured: false,
        rewardAmount: 0,
        wouldNeedReview: false,
        flags: ['SERVICE_SECRET_MISSING']
      });
      continue;
    }

    const payload = buildSmokePayload(source.serviceName, source.samplePayloads[0] || {});
    try {
      const result = await postRewardPayload({
        baseUrl,
        serviceName: source.serviceName,
        secret,
        payload,
        dryRun: true
      });
      rows.push({
        serviceName: source.serviceName,
        ok: result.ok,
        status: result.status,
        dryRunOk: Boolean(result.body?.dryRun?.ok),
        authConfigured: true,
        rewardAmount: Number(result.body?.dryRun?.rewardAmount || 0),
        wouldNeedReview: Boolean(result.body?.dryRun?.wouldNeedReview),
        flags: result.body?.dryRun?.flags || [],
        idempotencyKey: payload.idempotencyKey
      });
    } catch (err) {
      rows.push({
        serviceName: source.serviceName,
        ok: false,
        status: 0,
        dryRunOk: false,
        authConfigured: true,
        rewardAmount: 0,
        wouldNeedReview: false,
        flags: ['HTTP_SMOKE_ERROR'],
        error: err.message
      });
    }
  }

  const failed = rows.filter((row) => !row.ok);
  return {
    ok: failed.length === 0 && rows.length > 0,
    mode: 'reward-http-dry-run-smoke',
    baseUrl,
    totalServices: rows.length,
    passedServices: rows.length - failed.length,
    failedServices: failed.length,
    reviewServices: rows.filter((row) => row.wouldNeedReview).length,
    rows,
    failed,
    checkedAt: new Date().toISOString()
  };
}

module.exports = {
  runDryRunSmoke
};
