import { readFileSync, existsSync } from 'fs';
import path from 'path';

const DATA_DIR = process.env.CMS_DATA_DIR || '/app/data/content';

export function readData<T>(resource: string, fallback: T[]): T[] {
  const filePath = path.join(DATA_DIR, `${resource}.json`);
  try {
    if (existsSync(filePath)) {
      const raw = readFileSync(filePath, 'utf-8');
      return JSON.parse(raw) as T[];
    }
  } catch {
    // JSON parse error or read error — fall back to defaults
  }
  return fallback;
}

export function writeData<T>(resource: string, data: T[]): void {
  const { writeFileSync, mkdirSync } = require('fs') as typeof import('fs');
  mkdirSync(DATA_DIR, { recursive: true });
  const filePath = path.join(DATA_DIR, `${resource}.json`);
  writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');
}

export function validateAuth(request: Request): boolean {
  const password = request.headers.get('X-Admin-Password');
  const expected = process.env.ADMIN_PASSWORD;
  if (!expected) return false;
  return password === expected;
}
