import api from './client';

export const AuthApi = {
  async login(username, password) {
    const { data } = await api.post('/auth/login', { username, password });
    localStorage.setItem('access_token', data.access_token);
    localStorage.setItem('refresh_token', data.refresh_token);
    try {
      window.dispatchEvent(
        new CustomEvent('auth:changed', { detail: { loggedIn: true } }),
      );
    } catch (error) {
      console.error('Ошибка входа', error);
    }
    return data;
  },
  async refresh() {
    const refresh_token = localStorage.getItem('refresh_token');
    if (!refresh_token) return null;
    const { data } = await api.post('/auth/refresh', { refresh_token });
    localStorage.setItem('access_token', data.access_token);
    localStorage.setItem('refresh_token', data.refresh_token);
    return data;
  },
  logout() {
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
    try {
      window.dispatchEvent(
        new CustomEvent('auth:changed', { detail: { loggedIn: false } }),
      );
    } catch (error) {
      console.error('Ошибка при выходе', error);
    }
  },
};
