import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { authApi, AdminInfo } from '../infrastructure/auth.api';

interface AuthState {
  admin: AdminInfo | null;
  token: string | null;
  isAuthenticated: boolean;
  login: (username: string, password: string) => Promise<void>;
  logout: () => void;
  checkAuth: () => Promise<boolean>;
  hasPermission: (permission: string) => boolean;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      admin: null,
      token: null,
      isAuthenticated: false,

      login: async (username: string, password: string) => {
        const data = await authApi.login(username, password);
        localStorage.setItem('admin_token', data.token);
        set({
          admin: data.admin,
          token: data.token,
          isAuthenticated: true,
        });
      },

      logout: () => {
        localStorage.removeItem('admin_token');
        set({
          admin: null,
          token: null,
          isAuthenticated: false,
        });
      },

      checkAuth: async () => {
        const token = localStorage.getItem('admin_token');
        if (!token) {
          set({ isAuthenticated: false, admin: null, token: null });
          return false;
        }

        try {
          const admin = await authApi.verify();
          set({
            admin,
            token,
            isAuthenticated: true,
          });
          return true;
        } catch {
          localStorage.removeItem('admin_token');
        }

        set({ isAuthenticated: false, admin: null, token: null });
        return false;
      },

      hasPermission: (permission: string) => {
        const { admin } = get();
        if (!admin) return false;

        const permissions = admin.permissions || [];

        if (permissions.includes('*')) return true;
        if (permissions.includes(permission)) return true;

        const [resource] = permission.split(':');
        if (permissions.includes(`${resource}:*`)) return true;

        return false;
      },
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({
        admin: state.admin,
        token: state.token,
        isAuthenticated: state.isAuthenticated,
      }),
    }
  )
);
