import { apiPost } from './apiClient.js';

function isTokenExpired(token) {
  try {
    const payloadPart = token.split('.')[1];
    if (!payloadPart) return true;

    const base64 = payloadPart.replace(/-/g, '+').replace(/_/g, '/');
    const decoded = atob(base64);
    const payload = JSON.parse(decoded);

    if (!payload.exp) return false;
    return payload.exp * 1000 <= Date.now();
  } catch {
    return true;
  }
}

export class Auth {
  constructor() {
    this.currentUser = null;
    this.isAuthenticated = false;
  }

  async login(identifier, password) {
    if (!identifier || !password) return false;

    try {
      const body = { Username: identifier, Password: password };
      console.log('🔐 Login attempt - Datos enviados:', body);

      const data = await apiPost('/api/Auth/login', body, { auth: false });
      console.log('✅ Respuesta exitosa:', data);

      const { token, user } = data;
      if (!token) {
        console.error('❌ No token in response');
        return false;
      }

      this.currentUser = user || { identifier };
      this.isAuthenticated = true;
      localStorage.setItem('user', JSON.stringify(this.currentUser));
      localStorage.setItem('token', token);
      window.dispatchEvent(new Event('auth:login'));
      console.log('✅ Login successful, guardado en localStorage');
      return true;
    } catch (error) {
      console.error('❌ Login error:', error);
      return false;
    }
  }

  logout() {
    this.currentUser = null;
    this.isAuthenticated = false;
    localStorage.removeItem('user');
    localStorage.removeItem('token');
    window.dispatchEvent(new Event('auth:logout'));
  }

  checkAuth() {
    const user = localStorage.getItem('user');
    const token = localStorage.getItem('token');

    if (user && token && !isTokenExpired(token)) {
      this.currentUser = JSON.parse(user);
      this.isAuthenticated = true;
    } else {
      if (token && isTokenExpired(token)) {
        sessionStorage.setItem('session-expired-message', 'Tu sesion expiro. Inicia sesion de nuevo.');
      }
      this.isAuthenticated = false;
      this.currentUser = null;
      localStorage.removeItem('user');
      localStorage.removeItem('token');
      window.dispatchEvent(new Event('auth:logout'));
    }
    return this.isAuthenticated;
  }

  getUser() {
    return this.currentUser;
  }

  getToken() {
    return localStorage.getItem('token');
  }
}

export const auth = new Auth();
