require('../config/loadEnv')();

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

function getArg(name, fallback = '') {
  const prefix = `--${name}=`;
  const found = process.argv.find((arg) => arg.startsWith(prefix));
  return found ? found.slice(prefix.length) : fallback;
}

async function main() {
  const serviceName = String(getArg('service', process.env.REWARD_CLIENT_SERVICE || 'AISFOR')).trim().toUpperCase();
  const baseUrl = getArg('base-url', process.env.REWARD_CLIENT_BASE_URL || 'http://127.0.0.1:4317');
  const dryRun = getArg('live', '').toLowerCase() !== 'true';
  const secret = getServiceSecret(serviceName);
  if (!secret) throw new Error(`${serviceName} chain credential is not configured.`);

  const manifest = rewardPolicyService.getIntegrationManifest();
  const service = manifest.services.find((row) => row.serviceName === serviceName);
  if (!service || !service.samplePayloads.length) throw new Error(`${serviceName} sample payload is not available.`);

  const payload = {
    ...service.samplePayloads[0],
    idempotencyKey: `${serviceName}:CLI_EXAMPLE:${Date.now()}`
  };

  const result = await postRewardPayload({
    baseUrl,
    serviceName,
    secret,
    payload,
    dryRun
  });

  console.log(JSON.stringify({
    ok: result.ok,
    status: result.status,
    mode: dryRun ? 'dry-run' : 'live',
    serviceName,
    endpoint: result.url,
    wouldPersist: result.body?.wouldPersist ?? !dryRun,
    rewardAmount: result.body?.dryRun?.rewardAmount || result.body?.reward?.rewardAmount || 0,
    wouldNeedReview: Boolean(result.body?.dryRun?.wouldNeedReview),
    flags: result.body?.dryRun?.flags || result.body?.reward?.flags || [],
    idempotencyKey: payload.idempotencyKey
  }, null, 2));

  if (!result.ok) process.exitCode = 1;
}

main().catch((err) => {
  console.error(err.message);
  process.exitCode = 1;
});
