import AsyncStorage from '@react-native-async-storage/async-storage';
import { v4 as uuidv4 } from 'uuid';

const QUEUE_KEY = 'houseorg_sync_queue';

export type PendingOpType =
  | 'createItem'
  | 'updateItem'
  | 'deleteItem'
  | 'updateItemQuantity'
  | 'addToShoppingList'
  | 'checkOffItem'
  | 'removeShoppingEntry'
  | 'clearCheckedItems';

export type PendingOp = {
  id: string;
  ts: number;
  type: PendingOpType;
  payload: Record<string, unknown>;
};

async function readQueue(): Promise<PendingOp[]> {
  try {
    const raw = await AsyncStorage.getItem(QUEUE_KEY);
    return raw ? JSON.parse(raw) : [];
  } catch {
    return [];
  }
}

async function writeQueue(ops: PendingOp[]): Promise<void> {
  await AsyncStorage.setItem(QUEUE_KEY, JSON.stringify(ops));
}

export const syncQueue = {
  async add(op: Omit<PendingOp, 'id' | 'ts'>): Promise<void> {
    const ops = await readQueue();
    ops.push({ ...op, id: uuidv4(), ts: Date.now() });
    await writeQueue(ops);
  },

  async getAll(): Promise<PendingOp[]> {
    const ops = await readQueue();
    return ops.sort((a, b) => a.ts - b.ts);
  },

  async remove(id: string): Promise<void> {
    const ops = await readQueue();
    await writeQueue(ops.filter((op) => op.id !== id));
  },
};

export function isOfflineError(e: unknown): boolean {
  const msg = e instanceof Error ? e.message : String(e);
  return (
    msg.includes('Failed to fetch') ||
    msg.includes('Network request failed') ||
    msg.includes('NetworkError') ||
    msg.includes('network') ||
    (e as any)?.status === 0
  );
}
