/* ============ Database Layer — localStorage persistence ============ */

const DB_KEYS = {
  properties: 'casabilia-properties-db-v1',
  credentials: 'casabilia-credentials-db-v1',
  comps: 'casabilia-comps-cache-v1',
  deals: 'casabilia-deals-db-v1',
};

/* ---- Properties Database ---- */
function getPropertiesDB() {
  try { return JSON.parse(localStorage.getItem(DB_KEYS.properties)) || []; } catch (e) { return []; }
}
function savePropertiesDB(props) {
  try { localStorage.setItem(DB_KEYS.properties, JSON.stringify(props)); return true; } catch (e) { return false; }
}
function addProperty(prop) {
  const db = getPropertiesDB();
  const entry = {
    id: Date.now(),
    timestamp: new Date().toISOString(),
    address: prop.address || '',
    city: prop.city || '',
    state: prop.state || '',
    zip: prop.zip || '',
    sqft: prop.sqft || 0,
    beds: prop.beds || 0,
    baths: prop.baths || 0,
    subdivision: prop.subdivision || '',
    mls: prop.mls || '',
    price: prop.price || 0,
    status: prop.status || 'active', // active | closed | expired
    daysOnMarket: prop.daysOnMarket || 0,
    yearBuilt: prop.yearBuilt || 0,
    distance: prop.distance || 0,
    notes: prop.notes || '',
  };
  db.push(entry);
  savePropertiesDB(db);
  return entry;
}
function deleteProperty(id) {
  const db = getPropertiesDB();
  const filtered = db.filter((p) => p.id !== id);
  savePropertiesDB(filtered);
  return true;
}
function searchProperties(filters) {
  const db = getPropertiesDB();
  return db.filter((p) => {
    if (filters.sqftMin && p.sqft < filters.sqftMin) return false;
    if (filters.sqftMax && p.sqft > filters.sqftMax) return false;
    if (filters.beds && p.beds !== filters.beds) return false;
    if (filters.baths && p.baths !== filters.baths) return false;
    if (filters.subdivision && p.subdivision && !p.subdivision.toLowerCase().includes(filters.subdivision.toLowerCase())) return false;
    if (filters.status && p.status !== filters.status) return false;
    if (filters.city && p.city && !p.city.toLowerCase().includes(filters.city.toLowerCase())) return false;
    if (filters.state && p.state !== filters.state) return false;
    return true;
  });
}
function getPropertiesBySubdivision(subdivision, filters = {}) {
  return searchProperties({ subdivision, ...filters });
}

/* ---- Comps Cache Database ---- */
function getCompsCache() {
  try { return JSON.parse(localStorage.getItem(DB_KEYS.comps)) || {}; } catch (e) { return {}; }
}
function saveCompsCache(cache) {
  try { localStorage.setItem(DB_KEYS.comps, JSON.stringify(cache)); return true; } catch (e) { return false; }
}
function cacheComps(address, comps) {
  const cache = getCompsCache();
  cache[address] = {
    timestamp: Date.now(),
    data: comps,
  };
  saveCompsCache(cache);
}
function getCachedComps(address, maxAgeMins = 1440) {
  const cache = getCompsCache();
  const entry = cache[address];
  if (!entry) return null;
  const ageMs = Date.now() - entry.timestamp;
  if (ageMs > maxAgeMins * 60 * 1000) return null; // expired
  return entry.data;
}

/* ---- Credentials Database (partners/agents) ---- */
function getCredentialsDB() {
  try { return JSON.parse(localStorage.getItem(DB_KEYS.credentials)) || []; } catch (e) { return []; }
}
function saveCredentialsDB(creds) {
  try { localStorage.setItem(DB_KEYS.credentials, JSON.stringify(creds)); return true; } catch (e) { return false; }
}
function addCredential(cred) {
  const db = getCredentialsDB();
  // Simple hash (NOT secure — use backend for production!)
  const hash = btoa(cred.password || '');
  const entry = {
    id: Date.now(),
    username: cred.username || '',
    email: cred.email || '',
    role: cred.role || 'agent', // agent | partner | admin
    passwordHash: hash,
    createdAt: new Date().toISOString(),
    active: true,
  };
  db.push(entry);
  saveCredentialsDB(db);
  return { ...entry, passwordHash: '***' }; // don't return password
}
function verifyCredential(username, password) {
  const db = getCredentialsDB();
  const user = db.find((u) => u.username === username && u.active);
  if (!user) return null;
  const hash = btoa(password);
  if (user.passwordHash !== hash) return null;
  return { id: user.id, username: user.username, email: user.email, role: user.role };
}
function deleteCredential(id) {
  const db = getCredentialsDB();
  const filtered = db.map((c) => c.id === id ? { ...c, active: false } : c);
  saveCredentialsDB(filtered);
  return true;
}
function listUsers() {
  const db = getCredentialsDB();
  return db.filter((u) => u.active).map((u) => ({ id: u.id, username: u.username, email: u.email, role: u.role }));
}

/* ---- Deals Database ---- */
function getDealsDB() {
  try { return JSON.parse(localStorage.getItem(DB_KEYS.deals)) || []; } catch (e) { return []; }
}
function saveDealsDB(deals) {
  try { localStorage.setItem(DB_KEYS.deals, JSON.stringify(deals)); return true; } catch (e) { return false; }
}
function saveDealToDatabase(name, deal) {
  const db = getDealsDB();
  const entry = {
    id: Date.now(),
    name,
    address: deal.property.address,
    city: deal.property.city,
    savedAt: new Date().toISOString(),
    dealData: structuredClone(deal),
  };
  db.push(entry);
  saveDealsDB(db);
  return entry;
}
function loadDealFromDatabase(id) {
  const db = getDealsDB();
  const deal = db.find((d) => d.id === id);
  return deal ? deal.dealData : null;
}
function listSavedDeals() {
  return getDealsDB().map((d) => ({ id: d.id, name: d.name, address: d.address, city: d.city, savedAt: d.savedAt }));
}
function deleteDealFromDatabase(id) {
  const db = getDealsDB();
  const filtered = db.filter((d) => d.id !== id);
  saveDealsDB(filtered);
  return true;
}

/* ---- Sync point ---- */
Object.assign(window, {
  DB_KEYS,
  getPropertiesDB, savePropertiesDB, addProperty, deleteProperty, searchProperties, getPropertiesBySubdivision,
  getCompsCache, saveCompsCache, cacheComps, getCachedComps,
  getCredentialsDB, saveCredentialsDB, addCredential, verifyCredential, deleteCredential, listUsers,
  getDealsDB, saveDealsDB, saveDealToDatabase, loadDealFromDatabase, listSavedDeals, deleteDealFromDatabase,
});
