const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

const dataDir = path.join(__dirname, '..', 'data');
const approvalPath = path.join(dataDir, 'read-switch-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 && String(body.targetBackend || '') === 'mongodb';
  return {
    approved,
    targetBackend: body.targetBackend || '',
    approvedAt: body.approvedAt || null,
    approvedBy: body.approvedBy || '',
    revokedAt: body.revokedAt || null,
    revokedBy: body.revokedBy || '',
    approvalId: body.approvalId || '',
    path: approvalPath
  };
}

function approve({ targetBackend = 'mongodb', approvedBy = 'admin', reason = '' } = {}) {
  ensureDataDir();
  const now = new Date().toISOString();
  const body = {
    approved: true,
    targetBackend,
    approvedAt: now,
    approvedBy: String(approvedBy || 'admin'),
    reason: String(reason || 'manual admin approval'),
    approvalId: crypto.createHash('sha256').update(`${targetBackend}:${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 admin revoke')
  };
  fs.writeFileSync(approvalPath, `${JSON.stringify(body, null, 2)}\n`);
  return getApproval();
}

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