const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const rewardReadinessService = require('./rewardReadinessService');

const dataDir = path.join(__dirname, '..', 'data');
const approvalPath = path.join(dataDir, 'reward-live-canary-approval.json');

function ensureDataDir() {
  fs.mkdirSync(dataDir, { recursive: true });
}

function readJsonFile(filePath) {
  try {
    return JSON.parse(fs.readFileSync(filePath, 'utf8'));
  } catch (err) {
    return null;
  }
}

function getApproval() {
  const body = readJsonFile(approvalPath) || {};
  const approved = body.approved === true
    && body.confirmRequiredForLive === 'LIVE_SIMULATION_WRITE'
    && body.permitStatus === 'PERMITTED';

  return {
    approved,
    serviceName: body.serviceName || '',
    permitId: body.permitId || '',
    approvalId: body.approvalId || '',
    approvedAt: body.approvedAt || null,
    approvedBy: body.approvedBy || '',
    revokedAt: body.revokedAt || null,
    revokedBy: body.revokedBy || '',
    permitStatus: body.permitStatus || '',
    confirmRequiredForLive: body.confirmRequiredForLive || 'LIVE_SIMULATION_WRITE',
    liveCommand: body.liveCommand || '',
    dryRunCommand: body.dryRunCommand || '',
    reason: body.reason || '',
    path: approvalPath
  };
}

function approve({ approvedBy = 'admin', reason = '' } = {}) {
  const readiness = rewardReadinessService.getStatus();
  const permit = readiness.liveCanaryPermit || {};
  if (!permit.ok) {
    const err = new Error('Reward live canary permit is not ready.');
    err.status = 409;
    err.code = 'REWARD_CANARY_PERMIT_LOCKED';
    err.details = permit.failedChecks || [];
    throw err;
  }

  ensureDataDir();
  const now = new Date().toISOString();
  const body = {
    approved: true,
    approvedAt: now,
    approvedBy: String(approvedBy || 'admin'),
    reason: String(reason || 'manual reward live canary approval'),
    serviceName: permit.serviceName,
    permitId: permit.permitId,
    permitStatus: permit.status,
    confirmRequiredForLive: permit.confirmRequiredForLive,
    dryRunCommand: permit.dryRunCommand,
    liveCommand: permit.liveCommand,
    approvalId: crypto
      .createHash('sha256')
      .update(`${permit.serviceName}:${permit.permitId}:${now}:${approvedBy}`)
      .digest('hex')
      .slice(0, 24)
  };
  fs.writeFileSync(approvalPath, `${JSON.stringify(body, null, 2)}\n`);
  return getApproval();
}

function revoke({ revokedBy = 'admin', reason = '' } = {}) {
  ensureDataDir();
  const previous = readJsonFile(approvalPath) || {};
  const body = {
    ...previous,
    approved: false,
    revokedAt: new Date().toISOString(),
    revokedBy: String(revokedBy || 'admin'),
    revokeReason: String(reason || 'manual reward live canary revoke')
  };
  fs.writeFileSync(approvalPath, `${JSON.stringify(body, null, 2)}\n`);
  return getApproval();
}

module.exports = {
  approvalPath,
  getApproval,
  approve,
  revoke
};
