/**
 * @ai-summary Terms & Conditions configuration
 * @ai-context Static configuration for current T&C version, computed once at startup
 */

import { createHash } from 'crypto';
import { readFileSync, existsSync } from 'fs';
import { join } from 'path';
import { logger } from '../../../core/logging/logger';

// Current terms version and URL (update when PDF changes)
const TERMS_VERSION = 'v2026-01-03';
const TERMS_URL = '/docs/v2026-01-03.pdf';

// Compute hash once at module load (startup)
let termsContentHash: string | null = null;

function computeTermsHash(): string {
  if (termsContentHash) {
    return termsContentHash;
  }

  // In production, PDF is served by frontend; backend may not have access
  // For development, try to read from frontend/public/docs
  const possiblePaths = [
    join(__dirname, '../../../../../frontend/public/docs/v2026-01-03.pdf'),
    join(process.cwd(), 'frontend/public/docs/v2026-01-03.pdf'),
  ];

  for (const pdfPath of possiblePaths) {
    if (existsSync(pdfPath)) {
      try {
        const pdfContent = readFileSync(pdfPath);
        termsContentHash = createHash('sha256').update(pdfContent).digest('hex');
        logger.info('Terms content hash computed', {
          version: TERMS_VERSION,
          hash: termsContentHash.substring(0, 16) + '...'
        });
        return termsContentHash;
      } catch (error) {
        logger.warn('Failed to read terms PDF for hashing', { path: pdfPath, error });
      }
    }
  }

  // Fallback: use a placeholder hash (should be updated in production)
  // In production, this should be pre-computed and set as an environment variable
  termsContentHash = process.env['TERMS_CONTENT_HASH'] ||
    'placeholder-hash-update-in-production';

  logger.warn('Using fallback terms hash', {
    hash: termsContentHash.substring(0, 16) + '...',
    reason: 'PDF not found in development paths'
  });

  return termsContentHash;
}

export const termsConfig = {
  version: TERMS_VERSION,
  url: TERMS_URL,
  getContentHash: computeTermsHash,
};
