// Stockage simple dans un fichier JSON — aucune compilation, aucun module natif.
const fs = require('fs');
const path = require('path');
const FILE = path.join(__dirname, 'data.json');

let data = {
  users: [], biens: [], messages: [], avantages: [],
  content: {},
  seq: { users: 0, biens: 0, messages: 0, avantages: 0 }
};

function load() {
  try { data = JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (_) { /* premier démarrage */ }
  if (!data.users) data.users = [];
  if (!data.biens) data.biens = [];
  if (!data.messages) data.messages = [];
  if (!data.avantages) data.avantages = [];
  if (!data.content) data.content = {};
  if (!data.seq) data.seq = {};
  for (const k of ['users', 'biens', 'messages', 'avantages']) {
    if (typeof data.seq[k] !== 'number') data.seq[k] = 0;
  }
}
function save() { fs.writeFileSync(FILE, JSON.stringify(data, null, 2)); }
function now() { return new Date().toISOString().slice(0, 19).replace('T', ' '); }
function byPos(a, b) { return (a.position - b.position) || (a.id - b.id); }

function slugify(s) {
  return String(s || '').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '')
    .replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'bien';
}

function sanitizeTypo(t) {
  t = t || {};
  return {
    nom: String(t.nom || '').trim(),
    nb: String(t.nb || '').trim(),
    superficie: String(t.superficie || '').trim(),
    plan: String(t.plan || '').trim(),
    photo: String(t.photo || '').trim(),
    photos: String(t.photos || '').trim(),
    avantages: String(t.avantages || '').trim(),
    description: String(t.description || '').trim()
  };
}

function bienFields(o, current) {
  const cur = current || {};
  let photos = cur.photos || [];
  if (Array.isArray(o.photos)) photos = o.photos;
  photos = photos.filter(Boolean);
  let typologies = cur.typologies || [];
  if (Array.isArray(o.typologies)) typologies = o.typologies.map(sanitizeTypo).filter(t => t.nom || t.nb || t.superficie || t.plan || t.photo);
  return {
    categorie: (o.categorie === 'villa' ? 'villa' : 'residence'),
    titre: o.titre || '', typologie: o.typologie || '', lieu: o.lieu || '',
    adresse: (o.adresse !== undefined ? o.adresse : (cur.adresse || '')),
    map_query: (o.map_query !== undefined ? o.map_query : (cur.map_query || '')),
    avancement: (o.avancement !== undefined ? o.avancement : (cur.avancement || '')),
    unites: (o.unites !== undefined ? o.unites : (cur.unites || '')),
    prix: o.prix || '', surface: o.surface || '',
    chambres: o.chambres || '', detail: o.detail || '', exterieur: o.exterieur || '',
    description: o.description || '',
    equipements: o.equipements || '',
    commodites: (o.commodites !== undefined ? o.commodites : (cur.commodites || '')),
    palier: o.palier || '',
    palier_image: (o.palier_image !== undefined ? o.palier_image : (cur.palier_image || '')),
    typologies,
    photos,
    image: (o.image !== undefined ? o.image : (photos[0] || cur.image || '')),
    actif: o.actif ? 1 : 0, position: Number(o.position || 0)
  };
}
function avFields(o) {
  return {
    icon: o.icon || 'etoile', titre: o.titre || '', texte: o.texte || '',
    actif: o.actif ? 1 : 0, position: Number(o.position || 0)
  };
}

load();

module.exports = {
  // ---- Utilisateurs ----
  getUserByEmail(email) { return data.users.find(u => u.email === email) || null; },
  createUser(email, password_hash) {
    const u = { id: ++data.seq.users, email, password_hash, created_at: now() };
    data.users.push(u); save(); return u;
  },
  userCount() { return data.users.length; },
  allUsers() { return data.users.slice(); },
  setUserPassword(email, password_hash) {
    const u = data.users.find(x => x.email === String(email || '').trim().toLowerCase());
    if (!u) return null;
    u.password_hash = password_hash; save(); return u;
  },
  deleteUser(email) {
    const e = String(email || '').trim().toLowerCase();
    const i = data.users.findIndex(x => x.email === e);
    if (i === -1) return false;
    data.users.splice(i, 1); save(); return true;
  },

  // ---- Biens ----
  activeBiens() { return data.biens.filter(b => b.actif).sort(byPos); },
  activeBiensByCat(cat) {
    const c = (cat === 'villa' ? 'villa' : 'residence');
    return data.biens.filter(b => b.actif && (b.categorie || 'residence') === c).sort(byPos);
  },
  allBiens() { return [...data.biens].sort(byPos); },
  getBien(id) {
    return data.biens.find(b => String(b.id) === String(id) || (b.slug && b.slug === String(id))) || null;
  },
  createBien(o) {
    const b = { id: ++data.seq.biens, ...bienFields(o), created_at: now() };
    b.slug = slugify(b.titre) + '-' + b.id;
    data.biens.push(b); save(); return b;
  },
  updateBien(id, o) {
    const b = data.biens.find(x => String(x.id) === String(id));
    if (b) { Object.assign(b, bienFields(o, b)); b.slug = slugify(b.titre) + '-' + b.id; save(); }
  },
  deleteBien(id) { data.biens = data.biens.filter(b => String(b.id) !== String(id)); save(); },
  bienCount() { return data.biens.length; },

  // ---- Avantages (équipements) ----
  activeAvantages() { return data.avantages.filter(a => a.actif).sort(byPos); },
  allAvantages() { return [...data.avantages].sort(byPos); },
  getAvantage(id) { return data.avantages.find(a => String(a.id) === String(id)) || null; },
  createAvantage(o) {
    const a = { id: ++data.seq.avantages, ...avFields(o), created_at: now() };
    data.avantages.push(a); save(); return a;
  },
  updateAvantage(id, o) {
    const a = data.avantages.find(x => String(x.id) === String(id));
    if (a) { Object.assign(a, avFields(o)); save(); }
  },
  deleteAvantage(id) { data.avantages = data.avantages.filter(a => String(a.id) !== String(id)); save(); },
  avantageCount() { return data.avantages.length; },

  // ---- Contenu du site (textes) ----
  getContent() { return { ...data.content }; },
  getContentValue(key) { return data.content[key]; },
  setContent(obj) {
    for (const k of Object.keys(obj || {})) data.content[k] = obj[k];
    save();
  },
  contentCount() { return Object.keys(data.content).length; },

  // ---- Messages (demandes de contact) ----
  addMessage(m) {
    const x = { id: ++data.seq.messages, sujet: m.sujet || 'Contact', nom: m.nom, email: m.email, telephone: m.telephone || '', type_bien: m.type_bien || '', creneau: m.creneau || '', message: m.message, lu: 0, created_at: now() };
    data.messages.push(x); save(); return x;
  },
  allMessages() { return [...data.messages].sort((a, b) => b.id - a.id); },
  recentMessages(n) { return [...data.messages].sort((a, b) => b.id - a.id).slice(0, n); },
  messageCount() { return data.messages.length; },
  unreadCount() { return data.messages.filter(m => !m.lu).length; },
  markAllRead() { data.messages.forEach(m => m.lu = 1); save(); },
  deleteMessage(id) { data.messages = data.messages.filter(m => String(m.id) !== String(id)); save(); }
};
