import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";
import AsyncStorage from "@react-native-async-storage/async-storage";

interface PinState {
  hasPin: boolean;
  lastUnlockedAt: number | null;
  setHasPin: (value: boolean) => void;
  unlock: () => void;
  lock: () => void;
  isLocked: () => boolean;
}

export const usePinStore = create<PinState>()(
  persist(
    (set, get) => ({
      hasPin: false,
      lastUnlockedAt: null,
      setHasPin: (value) => set({ hasPin: value }),
      unlock: () => set({ lastUnlockedAt: Date.now() }),
      lock: () => set({ lastUnlockedAt: null }),
      isLocked: () => {
        const { hasPin, lastUnlockedAt } = get();
        if (!hasPin) return false;
        return lastUnlockedAt === null;
      },
    }),
    {
      name: "yaltopia-pin-storage",
      storage: createJSONStorage(() => AsyncStorage),
      partialize: (state) => ({ hasPin: state.hasPin }),
      merge: (persisted, current) => ({
        ...current,
        ...(persisted as object),
        lastUnlockedAt: null,
      }),
    },
  ),
);
