import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import bcrypt from 'bcryptjs';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data');
const CONTENT_FILE = path.join(DATA_DIR, 'content.json');
const ADMIN_FILE = path.join(DATA_DIR, 'admin.json');
const SEED_FILE = path.join(__dirname, 'seed', 'default-content.json');

function ensureDataDir() {
  if (!fs.existsSync(DATA_DIR)) {
    fs.mkdirSync(DATA_DIR, { recursive: true });
  }
}

function readJson(filePath, fallback = null) {
  if (!fs.existsSync(filePath)) return fallback;
  return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
}

function writeJson(filePath, data) {
  ensureDataDir();
  fs.writeFileSync(filePath, JSON.stringify(data, null, 2));
}

export function initDb() {
  ensureDataDir();

  if (!fs.existsSync(CONTENT_FILE)) {
    const seed = readJson(SEED_FILE);
    writeJson(CONTENT_FILE, { ...seed, updatedAt: new Date().toISOString() });
    console.log('Seeded content database from default-content.json');
  }

  if (!fs.existsSync(ADMIN_FILE)) {
    const password = process.env.ADMIN_PASSWORD || 'admin123';
    const hash = bcrypt.hashSync(password, 12);
    writeJson(ADMIN_FILE, {
      username: process.env.ADMIN_USERNAME || 'admin',
      passwordHash: hash,
    });
    console.log(`Admin user created (username: ${process.env.ADMIN_USERNAME || 'admin'})`);
  }
}

export function getContent() {
  const data = readJson(CONTENT_FILE, {});
  const { updatedAt, ...content } = data;
  return { content, updatedAt };
}

export function getFullContentRecord() {
  return readJson(CONTENT_FILE, {});
}

export function updateSection(section, sectionData) {
  const record = getFullContentRecord();
  record[section] = sectionData;
  record.updatedAt = new Date().toISOString();
  writeJson(CONTENT_FILE, record);
  return record.updatedAt;
}

export function updateAllContent(content) {
  const record = { ...content, updatedAt: new Date().toISOString() };
  writeJson(CONTENT_FILE, record);
  return record.updatedAt;
}

export function getAdmin() {
  return readJson(ADMIN_FILE);
}

export function updateAdminPassword(passwordHash) {
  const admin = getAdmin();
  admin.passwordHash = passwordHash;
  writeJson(ADMIN_FILE, admin);
}
