const DB_KEY = 'shire_dental_db_v1';
const AUTH_KEY = 'shire_dental_auth_v1';

const seed = { Patient: [], DentalCase: [], AuditLog: [] };
const loadDb = () => { try { return { ...seed, ...JSON.parse(localStorage.getItem(DB_KEY) || '{}') }; } catch { return { ...seed }; } };
const saveDb = (db) => localStorage.setItem(DB_KEY, JSON.stringify(db));
const uid = () => globalThis.crypto?.randomUUID?.() || `sd-${Date.now()}-${Math.random().toString(16).slice(2)}`;

function entity(name) {
  return {
    async list(order = '-created_date') {
      const rows = [...(loadDb()[name] || [])];
      const desc = order.startsWith('-');
      const key = order.replace(/^-/, '');
      return rows.sort((a,b) => String(a[key] || '').localeCompare(String(b[key] || '')) * (desc ? -1 : 1));
    },
    async create(values) {
      const db = loadDb();
      const row = { id: uid(), created_date: new Date().toISOString(), ...values };
      db[name] = [...(db[name] || []), row]; saveDb(db); return row;
    },
    async update(id, values) {
      const db = loadDb();
      db[name] = (db[name] || []).map(r => r.id === id ? { ...r, ...values, updated_date: new Date().toISOString() } : r);
      saveDb(db); return db[name].find(r => r.id === id);
    },
    async delete(id) {
      const db = loadDb(); db[name] = (db[name] || []).filter(r => r.id !== id); saveDb(db); return true;
    }
  };
}

const auth = {
  async me() { const user = JSON.parse(localStorage.getItem(AUTH_KEY) || 'null'); if (!user) throw new Error('auth_required'); return user; },
  async loginViaEmailPassword(email, password) {
    if (!email || !password) throw new Error('Email and password required');
    const user = { id: uid(), email, full_name: email.split('@')[0], role: 'administrator' };
    localStorage.setItem(AUTH_KEY, JSON.stringify(user)); return user;
  },
  async register({ email, password }) { return this.loginViaEmailPassword(email, password); },
  async verifyOtp({ email }) { const user = await this.loginViaEmailPassword(email, 'verified'); return { access_token: 'local-session', user }; },
  async resendOtp() { return true; },
  async resetPasswordRequest() { return true; },
  async resetPassword() { return true; },
  loginWithProvider() { throw new Error('Social login requires your own OAuth provider configuration.'); },
  setToken() {},
  logout(redirect = '/login') { localStorage.removeItem(AUTH_KEY); if (redirect) window.location.assign(redirect); },
  redirectToLogin() { window.location.assign('/login'); }
};

export const studioClient = {
  auth,
  entities: new Proxy({}, { get: (_, name) => entity(name) }),
  exportData() { return JSON.stringify(loadDb(), null, 2); },
  importData(json) { const parsed = JSON.parse(json); saveDb({ ...seed, ...parsed }); }
};
