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

const {
  SERVICE_ENV_KEYS,
  getConfiguredServices,
  isAuthRequired
} = require('../config/serviceCredentials');
const rewardPolicyService = require('../services/rewardPolicyService');

const configured = new Set(getConfiguredServices());
const services = rewardPolicyService.getPolicy().sources
  .filter((source) => source.serviceName !== 'AISFOR_CHAIN')
  .map((source) => ({
    serviceName: source.serviceName,
    status: source.status,
    envKey: SERVICE_ENV_KEYS[source.serviceName] || '',
    configured: configured.has(source.serviceName),
    endpoint: source.endpoint
  }));

const required = isAuthRequired();
const missing = services.filter((service) => !service.configured);
const result = {
  ok: required ? missing.length === 0 : services.some((service) => service.configured),
  mode: 'reward-service-auth-check',
  authRequired: required,
  configuredServices: Array.from(configured),
  totalExternalServices: services.length,
  configuredExternalServices: services.length - missing.length,
  missing,
  services,
  headers: {
    service: 'X-AISFOR-SERVICE',
    apiKey: 'X-AISFOR-API-KEY',
    signature: 'X-AISFOR-SIGNATURE',
    timestamp: 'X-AISFOR-TIMESTAMP',
    nonce: 'X-AISFOR-NONCE'
  },
  checkedAt: new Date().toISOString()
};

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

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