import { create } from 'zustand';
import { login as apiLogin, logout as apiLogout, type UserInfo } from '../api/auth';
import { clearApiCache } from '../api/client';

function extractPermissions(): string[] {
  const token = localStorage.getItem('access_token');
  if (!token) return [];
  try {
    const parts = token.split('.');
    if (parts.length !== 3) return [];
    const payload = JSON.parse(atob(parts[1].replace(/-/g, '+').replace(/_/g, '/')));
    return Array.isArray(payload.permissions) ? payload.permissions : [];
  } catch {
    return [];
  }
}

function restoreInitialState(): { user: UserInfo | null; isAuthenticated: boolean; permissions: string[] } {
  const token = localStorage.getItem('access_token');
  const userStr = localStorage.getItem('user');
  if (token && userStr) {
    try {
      const user = JSON.parse(userStr) as UserInfo;
      return { user, isAuthenticated: true, permissions: extractPermissions() };
    } catch {
      localStorage.removeItem('user');
    }
  }
  return { user: null, isAuthenticated: false, permissions: [] };
}

const initial = restoreInitialState();

interface AuthState {
  user: UserInfo | null;
  isAuthenticated: boolean;
  loading: boolean;
  permissions: string[];
  login: (username: string, password: string) => Promise<void>;
  logout: () => Promise<void>;
  loadFromStorage: () => void;
}

export const useAuthStore = create<AuthState>((set) => ({
  user: initial.user,
  isAuthenticated: initial.isAuthenticated,
  loading: false,
  permissions: initial.permissions,

  login: async (username, password) => {
    set({ loading: true });
    try {
      const resp = await apiLogin({ username, password });
      localStorage.setItem('access_token', resp.access_token);
      localStorage.setItem('refresh_token', resp.refresh_token);
      localStorage.setItem('user', JSON.stringify(resp.user));
      set({ user: resp.user, isAuthenticated: true, loading: false, permissions: extractPermissions() });
      clearApiCache();
    } catch (error) {
      set({ loading: false });
      throw error;
    }
  },

  logout: async () => {
    try {
      await apiLogout();
    } catch {
      // Ignore logout API errors
    }
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
    localStorage.removeItem('user');
    clearApiCache();
    set({ user: null, isAuthenticated: false, permissions: [] });
  },

  loadFromStorage: () => {
    const state = restoreInitialState();
    set({ user: state.user, isAuthenticated: state.isAuthenticated, permissions: state.permissions });
  },
}));
