import { defineStore } from "pinia";
import { ref } from "vue";

/**
 * Wraith application store.
 * Manages unlock state, first-run detection, and vault operations.
 *
 * Once Wails v3 bindings are generated, the mock calls below will be
 * replaced with actual WraithApp.IsFirstRun(), CreateVault(), Unlock(), etc.
 */
export const useAppStore = defineStore("app", () => {
  const isUnlocked = ref(false);
  const isFirstRun = ref(true);
  const isLoading = ref(true);
  const error = ref<string | null>(null);

  /** Check whether the vault has been created before. */
  async function checkFirstRun(): Promise<void> {
    try {
      // TODO: replace with Wails binding — WraithApp.IsFirstRun()
      isFirstRun.value = true;
    } catch {
      isFirstRun.value = true;
    } finally {
      isLoading.value = false;
    }
  }

  /** Create a new vault with the given master password. */
  async function createVault(password: string): Promise<void> {
    error.value = null;
    try {
      // TODO: replace with Wails binding — WraithApp.CreateVault(password)
      void password;
      isFirstRun.value = false;
      isUnlocked.value = true;
    } catch (e) {
      error.value = e instanceof Error ? e.message : "Failed to create vault";
      throw e;
    }
  }

  /** Unlock an existing vault with the master password. */
  async function unlock(password: string): Promise<void> {
    error.value = null;
    try {
      // TODO: replace with Wails binding — WraithApp.Unlock(password)
      void password;
      isUnlocked.value = true;
    } catch (e) {
      error.value = e instanceof Error ? e.message : "Invalid master password";
      throw e;
    }
  }

  /** Lock the vault (return to unlock screen). */
  function lock(): void {
    isUnlocked.value = false;
  }

  /** Clear the current error message. */
  function clearError(): void {
    error.value = null;
  }

  return {
    isUnlocked,
    isFirstRun,
    isLoading,
    error,
    checkFirstRun,
    createVault,
    unlock,
    lock,
    clearError,
  };
});
