const express = require('express');
const blockService = require('../services/blockService');
const rewardAuditService = require('../services/rewardAuditService');
const rewardLedgerService = require('../services/rewardLedgerService');
const rewardLiveCanaryApprovalService = require('../services/rewardLiveCanaryApprovalService');
const rewardPolicyService = require('../services/rewardPolicyService');
const rewardReadinessService = require('../services/rewardReadinessService');
const rewardReviewService = require('../services/rewardReviewService');
const { requireServiceAuth } = require('../middleware/serviceAuth');

const router = express.Router();

router.get('/', (req, res) => {
  res.json({
    ok: true,
    stats: rewardLedgerService.getStats(),
    rewards: rewardLedgerService.listEntries()
  });
});

router.get('/sources', (req, res) => {
  const policy = rewardPolicyService.getPolicy();
  res.json({
    ok: true,
    sources: policy.sources,
    categories: policy.categories,
    settlement: policy.settlement
  });
});

router.get('/manifest', (req, res) => {
  res.json({
    ok: true,
    manifest: rewardPolicyService.getIntegrationManifest()
  });
});

router.get('/readiness', (req, res) => {
  res.json({
    ok: true,
    readiness: rewardReadinessService.getStatus()
  });
});

router.get('/live-canary-permit', (req, res) => {
  const readiness = rewardReadinessService.getStatus();
  res.json({
    ok: true,
    permit: readiness.liveCanaryPermit
  });
});

router.get('/live-canary-approval', (req, res) => {
  res.json({
    ok: true,
    approval: rewardLiveCanaryApprovalService.getApproval()
  });
});

router.get('/audit', (req, res) => {
  res.json({
    ok: true,
    stats: rewardAuditService.getStats(),
    audit: rewardAuditService.listEntries()
  });
});

router.get('/review', (req, res) => {
  res.json({
    ok: true,
    count: rewardLedgerService.getStats().reviewCount,
    decisions: rewardReviewService.getStats(),
    rewards: rewardLedgerService.getReviewQueue()
  });
});

router.get('/review-decisions', (req, res) => {
  res.json({
    ok: true,
    stats: rewardReviewService.getStats(),
    decisions: rewardReviewService.listDecisions()
  });
});

router.post('/review-decisions/repair-anchors', requireServiceAuth, async (req, res, next) => {
  try {
    const result = await rewardReviewService.repairAnchors({
      limit: req.body.limit || 25,
      reviewer: req.serviceIdentity?.serviceName || req.body.reviewer || 'service-anchor-repair'
    });
    res.status(200).json(result);
  } catch (err) {
    next(err);
  }
});

router.post('/dry-run', requireServiceAuth, (req, res, next) => {
  try {
    const validation = rewardPolicyService.validateRewardSubmission(req.body || {});
    const dryRun = rewardLedgerService.dryRunExternalPointReward({
      ...(req.body || {}),
      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
      }
    });
    res.status(200).json({
      ok: validation.ok && dryRun.ok,
      mode: 'reward-dry-run',
      wouldPersist: false,
      validation,
      serviceIdentity: req.serviceIdentity,
      dryRun
    });
  } catch (err) {
    next(err);
  }
});

router.post('/:rewardId/review', requireServiceAuth, async (req, res, next) => {
  try {
    const decision = await rewardReviewService.recordDecision({
      rewardId: req.params.rewardId,
      decision: req.body.decision,
      reviewer: req.serviceIdentity?.serviceName || req.body.reviewer || 'service-operator',
      reason: req.body.reason || ''
    });
    res.status(201).json({ ok: true, decision });
  } catch (err) {
    next(err);
  }
});

router.post('/', requireServiceAuth, (req, res, next) => {
  try {
    const validation = rewardPolicyService.validateRewardSubmission(req.body || {});
    const reward = rewardLedgerService.createExternalPointReward({
      ...(req.body || {}),
      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
      }
    });
    const audit = rewardAuditService.recordAccepted({
      payload: req.body || {},
      validation: {
        ok: validation.ok,
        sourceService: validation.sourceService,
        category: validation.category,
        actionType: validation.actionType,
        flags: validation.flags,
        warnings: validation.warnings
      },
      reward,
      serviceIdentity: req.serviceIdentity
    });
    const mined = blockService.minePendingProofs({
      limit: Number(process.env.AISFOR_CHAIN_REWARD_AUTO_MINE_SIZE || 10),
      reason: 'reward-ledger-entry'
    });
    res.status(201).json({
      ok: true,
      validation,
      serviceIdentity: req.serviceIdentity,
      reward,
      audit,
      mined
    });
  } catch (err) {
    next(err);
  }
});

module.exports = router;
