import { create } from 'zustand';
import { api } from '../../services/api';

type User = {
  id: number;
  username: string;
  roles: string[];
};

type AuthStore = {
  user: User | null;
  token: string | null;
  isLoggedIn: boolean;
  login: (username: string, password: string) => Promise<void>;
  logout: () => void;
};

export const useAuthStore = create<AuthStore>((set) => ({
  user: JSON.parse(localStorage.getItem('user') || 'null'),
  token: localStorage.getItem('token'),
  isLoggedIn: !!localStorage.getItem('token'),

  login: async (username: string, password: string) => {
    try {
      const response = await api('post', '/api/v1/app/users/login', { username, password });
      const { success, data } = response.data;

      if (success) {
        const { token, user } = data;
        localStorage.setItem('user', JSON.stringify(user));
        localStorage.setItem('token', token);

        set({ user, token, isLoggedIn: true });
      } else {
        throw new Error('Login failed');
      }
    } catch (error) {
      console.error('Failed to login:', error);
      throw new Error('Login failed');
    }
  },

  logout: () => {
    localStorage.removeItem('user');
    localStorage.removeItem('token');
    set({ user: null, token: null, isLoggedIn: false });
  },
}));

function parseJwt(token) {
  const base64Url = token.split('.')[1];
  const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
  const jsonPayload = decodeURIComponent(
    atob(base64)
      .split('')
      .map(function (c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
      })
      .join('')
  );

  return JSON.parse(jsonPayload);
}
