const API_URL = `${import.meta.env.VITE_API_URL}/auth`;

export const publicAuthService = {
  login: async (username: string, password: string) => {
    const response = await fetch(`${API_URL}/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username, password })
    });
    const data = await response.json();
    if (response.ok && data.token) {
      localStorage.setItem('public_token', data.token);
      localStorage.setItem('public_user', JSON.stringify({ username }));
    }
    return data;
  },

  register: async (username: string, email: string, password: string) => {
    const response = await fetch(`${API_URL}/register`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username, email, password })
    });
    return await response.json();
  },

  googleLogin: async (idToken: string) => {
    const response = await fetch(`${API_URL}/google-login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(idToken)
    });
    const data = await response.json();
    if (response.ok && data.token) {
      localStorage.setItem('public_token', data.token);
    }
    return data;
  },

  setupMfa: async () => {
    const token = localStorage.getItem('public_token');
    const response = await fetch(`${API_URL}/mfa/setup`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });
    return await response.json();
  },

  verifyMfa: async (code: string) => {
    const token = localStorage.getItem('public_token');
    const response = await fetch(`${API_URL}/mfa/verify`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify(code)
    });
    return await response.json();
  },

  logout: () => {
    localStorage.removeItem('public_token');
    localStorage.removeItem('public_user');
  },

  isAuthenticated: () => !!localStorage.getItem('public_token')
};
