import { writable } from 'svelte/store';
import type { User } from '$lib/api/client';

interface AuthState {
  user: User | null;
  token: string | null;
  loading: boolean;
}

function createAuthStore() {
  const { subscribe, set, update } = writable<AuthState>({
    user: null,
    token: null,
    loading: true,
  });

  return {
    subscribe,
    login: (user: User, token: string) => {
      localStorage.setItem('token', token);
      set({ user, token, loading: false });
    },
    logout: () => {
      localStorage.removeItem('token');
      set({ user: null, token: null, loading: false });
    },
    init: () => {
      const token = localStorage.getItem('token');
      if (token) {
        set({ user: null, token, loading: false });
      } else {
        set({ user: null, token: null, loading: false });
      }
    },
  };
}

export const auth = createAuthStore();
