import AsyncStorage from '@react-native-async-storage/async-storage';

const PREFIX = 'nova40_data_';

function key(collection, id) {
  return id ? `${PREFIX}${collection}_${id}` : `${PREFIX}${collection}`;
}

function generateId() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = (Math.random() * 16) | 0;
    const v = c === 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

// Get all items in a collection for a given filter
async function getCollection(collection) {
  const raw = await AsyncStorage.getItem(key(collection));
  return raw ? JSON.parse(raw) : [];
}

async function saveCollection(collection, items) {
  await AsyncStorage.setItem(key(collection), JSON.stringify(items));
}

// --- CRUD helpers ---

export async function getAll(collection, filter = {}) {
  const items = await getCollection(collection);
  return items.filter((item) => {
    for (const [k, v] of Object.entries(filter)) {
      if (item[k] !== v) return false;
    }
    return true;
  });
}

export async function getOne(collection, filter = {}) {
  const items = await getAll(collection, filter);
  return items[0] || null;
}

export async function insert(collection, data) {
  const items = await getCollection(collection);
  const newItem = { id: generateId(), ...data, created_at: new Date().toISOString() };
  items.push(newItem);
  await saveCollection(collection, items);
  return newItem;
}

export async function insertMany(collection, dataArray) {
  const items = await getCollection(collection);
  const newItems = dataArray.map((d) => ({
    id: generateId(),
    ...d,
    created_at: new Date().toISOString(),
  }));
  items.push(...newItems);
  await saveCollection(collection, items);
  return newItems;
}

export async function update(collection, filter, updates) {
  const items = await getCollection(collection);
  let updated = null;
  const newItems = items.map((item) => {
    const matches = Object.entries(filter).every(([k, v]) => item[k] === v);
    if (matches && !updated) {
      updated = { ...item, ...updates };
      return updated;
    }
    return item;
  });
  await saveCollection(collection, newItems);
  return updated;
}

export async function upsert(collection, filter, data) {
  const existing = await getOne(collection, filter);
  if (existing) {
    return update(collection, { id: existing.id }, data);
  }
  return insert(collection, { ...filter, ...data });
}

export async function removeAll(collection, filter = {}) {
  const items = await getCollection(collection);
  const filtered = items.filter((item) => {
    for (const [k, v] of Object.entries(filter)) {
      if (item[k] !== v) return true;
    }
    return false;
  });
  await saveCollection(collection, filtered);
}
