import { defineStore } from "pinia";
import { ref } from "vue";
import { Call } from "@wailsio/runtime";

/** Fully qualified Go method name prefix for WraithApp bindings. */
const APP = "github.com/vstockwell/wraith/internal/app.WraithApp";

/**
 * Wraith application store.
 * Manages unlock state, first-run detection, and vault operations.
 */
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 {
      isFirstRun.value = await Call.ByName(`${APP}.IsFirstRun`) as boolean;
    } 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 {
      await Call.ByName(`${APP}.CreateVault`, password);
      isFirstRun.value = false;
      isUnlocked.value = true;
    } catch (e) {
      error.value = e instanceof Error ? e.message : String(e) || "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 {
      await Call.ByName(`${APP}.Unlock`, password);
      isUnlocked.value = true;
    } catch (e) {
      error.value = e instanceof Error ? e.message : String(e) || "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,
  };
});
