import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { MeResp } from '../api/auth';

interface AuthState {
  accessToken: string | null;
  refreshToken: string | null;
  profile: MeResp | null;
  setSession: (access: string, refresh: string, profile: MeResp) => void;
  setAccessToken: (access: string) => void;
  setProfile: (profile: MeResp) => void;
  clear: () => void;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set) => ({
      accessToken: null,
      refreshToken: null,
      profile: null,
      setSession: (access, refresh, profile) => {
        localStorage.setItem('mobile.accessToken', access);
        localStorage.setItem('mobile.refreshToken', refresh);
        set({ accessToken: access, refreshToken: refresh, profile });
      },
      setAccessToken: (access) => {
        localStorage.setItem('mobile.accessToken', access);
        set({ accessToken: access });
      },
      setProfile: (profile) => set({ profile }),
      clear: () => {
        localStorage.removeItem('mobile.accessToken');
        localStorage.removeItem('mobile.refreshToken');
        set({ accessToken: null, refreshToken: null, profile: null });
      },
    }),
    { name: 'mobile.profile' },
  ),
);
