import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { User } from '../types';

interface UserState {
  users: User[];
  activeUser: User | null;
  setActiveUser: (user: User) => void;
  fetchUsers: () => Promise<void>;
  createUser: (name: string) => Promise<User | null>;
  deleteUser: (id: number) => Promise<boolean>;
}

export const useUserStore = create<UserState>()(
  persist(
    (set, get) => ({
      users: [],
      activeUser: null,

      setActiveUser: (user) => set({ activeUser: user }),

      fetchUsers: async () => {
        const res = await fetch('/api/v1/users', {
          headers: { 'Content-Type': 'application/json' },
        });
        if (!res.ok) return;
        const users: User[] = await res.json();
        set({ users });

        // Aktiven Nutzer aktualisieren falls er sich geändert hat
        const { activeUser } = get();
        if (activeUser) {
          const updated = users.find((u) => u.id === activeUser.id);
          if (updated) set({ activeUser: updated });
        }
      },

      createUser: async (name) => {
        const res = await fetch('/api/v1/users', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ name }),
        });
        if (!res.ok) return null;
        const user: User = await res.json();
        set((s) => ({ users: [...s.users, user] }));
        return user;
      },

      deleteUser: async (id) => {
        const res = await fetch(`/api/v1/users/${id}`, { method: 'DELETE' });
        if (!res.ok) return false;
        set((s) => ({
          users: s.users.filter((u) => u.id !== id),
          activeUser: s.activeUser?.id === id ? null : s.activeUser,
        }));
        return true;
      },
    }),
    {
      name: 'user-store',
      partialize: (state) => ({ activeUser: state.activeUser }),
    },
  ),
);

// Gibt die aktive User-ID zurück — wird von api/client.ts verwendet.
export function getActiveUserId(): string | null {
  const { activeUser } = useUserStore.getState();
  return activeUser ? String(activeUser.id) : null;
}
