let worker: Worker | null = null;
const pendingRequests = new Map<string, { resolve: Function; reject: Function }>();

export const initDB = async () => {
  if (worker) return;

  // Initialize Web Worker using Vite-friendly URL syntax
  worker = new Worker(
    new URL('./db.worker.ts', import.meta.url),
    { type: 'module' }
  );

  worker.onmessage = (event) => {
    const { id, success, result, error } = event.data;
    const pending = pendingRequests.get(id);
    if (pending) {
      pendingRequests.delete(id);
      if (success) {
        pending.resolve(result);
      } else {
        pending.reject(new Error(error));
      }
    }
  };
};

const sendToWorker = (type: 'query' | 'execute' | 'verifyPassword' | 'cacheHash' | 'createLocalUser', sql: string, params: any[] = []) => {
  if (!worker) {
    throw new Error('Database not initialized. Call initDB() first.');
  }
  return new Promise((resolve, reject) => {
    const id = Math.random().toString(36).substring(2, 9);
    pendingRequests.set(id, { resolve, reject });
    worker!.postMessage({ type, id, sql, params });
  });
};

export const query = async (sql: string, params: any[] = []): Promise<any[]> => {
  return sendToWorker('query', sql, params) as Promise<any[]>;
};

export const execute = async (sql: string, params: any[] = []): Promise<void> => {
  await sendToWorker('execute', sql, params);
};

export const verifyPassword = async (email: string, password: string): Promise<{ ok: boolean; user?: any; reason?: string }> => {
  return sendToWorker('verifyPassword', '', [email, password]) as Promise<{ ok: boolean; user?: any; reason?: string }>;
};

export const cacheHash = async (email: string, passwordHash: string): Promise<void> => {
  await sendToWorker('cacheHash', '', [email, passwordHash]);
};

export const createLocalUser = async (userData: Record<string, any>): Promise<{ ok: boolean; user?: any; reason?: string }> => {
  return sendToWorker('createLocalUser', '', [userData]) as Promise<{ ok: boolean; user?: any; reason?: string }>;
};

// Dummy getDB to prevent compilation issues, but it should not be called directly
export const getDB = () => {
  console.warn('getDB() is deprecated when running inside a worker context.');
  return null;
};
