const LEGACY_USER_STORAGE_KEY = "nebula.user.v1";

const getInvoke = async () => {
  const globalInvoke = window.__TAURI__?.core?.invoke;
  if (typeof globalInvoke === "function") {
    return globalInvoke;
  }

  try {
    const tauriCore = await import("@tauri-apps/api/core");
    return typeof tauriCore.invoke === "function" ? tauriCore.invoke : null;
  } catch (_error) {
    return null;
  }
};

const normalizeUser = (record) => {
  if (!record || typeof record !== "object") {
    return null;
  }
  const id = Number(record.id);
  const name = typeof record.name === "string" ? record.name.trim() : "";
  const firstName = typeof record.firstName === "string" ? record.firstName.trim() : "";
  const lastName = typeof record.lastName === "string" ? record.lastName.trim() : "";
  if (!Number.isFinite(id) || !name) {
    return null;
  }

  return {
    id,
    name,
    firstName: firstName || name,
    lastName: lastName || "",
    createdAtUnixMs: Number(record.createdAtUnixMs ?? Date.now()),
  };
};

export const loadExistingUser = async () => {
  const invoke = await getInvoke();
  if (!invoke) {
    const legacyRaw = window.localStorage.getItem(LEGACY_USER_STORAGE_KEY);
    if (!legacyRaw) {
      return null;
    }
    try {
      return normalizeUser(JSON.parse(legacyRaw));
    } catch (_parseError) {
      return null;
    }
  }

  try {
    const record = await invoke("get_first_user");
    return normalizeUser(record);
  } catch (_error) {
    const legacyRaw = window.localStorage.getItem(LEGACY_USER_STORAGE_KEY);
    if (!legacyRaw) {
      return null;
    }
    try {
      return normalizeUser(JSON.parse(legacyRaw));
    } catch (_parseError) {
      return null;
    }
  }
};

export const createUser = async ({ firstName, lastName = "" }) => {
  const requestedFirstName = String(firstName ?? "").trim();
  const requestedLastName = String(lastName ?? "").trim();
  if (!requestedFirstName) {
    throw new Error("First name is required.");
  }

  const invoke = await getInvoke();
  if (!invoke) {
    const fallback = {
      id: 1,
      name: requestedLastName ? `${requestedFirstName} ${requestedLastName}` : requestedFirstName,
      firstName: requestedFirstName,
      lastName: requestedLastName,
      createdAtUnixMs: Date.now(),
    };
    window.localStorage.setItem(LEGACY_USER_STORAGE_KEY, JSON.stringify(fallback));
    return fallback;
  }

  try {
    const record = await invoke("create_user", {
      firstName: requestedFirstName,
      lastName: requestedLastName || null,
    });
    return normalizeUser(record);
  } catch (_error) {
    const fallback = {
      id: 1,
      name: requestedLastName ? `${requestedFirstName} ${requestedLastName}` : requestedFirstName,
      firstName: requestedFirstName,
      lastName: requestedLastName,
      createdAtUnixMs: Date.now(),
    };
    window.localStorage.setItem(LEGACY_USER_STORAGE_KEY, JSON.stringify(fallback));
    return fallback;
  }
};
