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

const rewardLedgerService = require('../services/rewardLedgerService');
const rewardPolicyService = require('../services/rewardPolicyService');

const manifest = rewardPolicyService.getIntegrationManifest();
const rows = manifest.services.flatMap((source) => (
  (source.samplePayloads || []).map((payload) => {
    const validation = rewardPolicyService.validateRewardSubmission(payload);
    const dryRun = rewardLedgerService.dryRunExternalPointReward({
      ...payload,
      sourcePolicyFlags: validation.flags,
      sourcePolicyWarnings: validation.warnings,
      sourcePolicyValidation: {
        ok: validation.ok,
        sourceService: validation.sourceService,
        category: validation.category,
        actionType: validation.actionType,
        flags: validation.flags,
        warnings: validation.warnings
      }
    });
    return {
      serviceName: source.serviceName,
      category: payload.category,
      actionType: payload.actionType,
      ok: validation.ok && dryRun.ok,
      validationOk: validation.ok,
      dryRunOk: dryRun.ok,
      wouldNeedReview: dryRun.wouldNeedReview,
      rewardAmount: dryRun.rewardAmount,
      flags: dryRun.flags
    };
  })
));

const failed = rows.filter((row) => !row.ok);
const reviewRows = rows.filter((row) => row.wouldNeedReview);
const result = {
  ok: failed.length === 0,
  mode: 'reward-dry-run-manifest-check',
  totalSamples: rows.length,
  passedSamples: rows.length - failed.length,
  failedSamples: failed.length,
  reviewSamples: reviewRows.length,
  failed,
  reviewRows,
  checkedAt: new Date().toISOString()
};

console.log(JSON.stringify(result, null, 2));

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