import axios from 'axios';
import API_BASE_URL from '../config/api';

class AuthService {
  constructor() {
    this.api = axios.create({
      baseURL: API_BASE_URL,
      headers: {
        'Content-Type': 'application/json'
      },
      withCredentials: true // Enable sending cookies with requests
    });


    // Handle authentication errors (401/403) but don't auto-redirect on network errors
    this.api.interceptors.response.use(
      (response) => response,
      (error) => {
        // Only auto-logout on explicit authentication errors, not network issues
        if (error.response && (error.response.status === 401 || error.response.status === 403)) {
          this.logout();
          // Only redirect if not already on auth page to avoid redirect loops
          if (window.location.pathname !== '/auth') {
            window.location.href = '/auth';
          }
        }
        return Promise.reject(error);
      }
    );
  }

  async register(userData) {
    const response = await this.api.post('/auth/register', userData);
    return response.data;
  }

  async login(credentials) {
    const response = await this.api.post('/auth/login', credentials);
    // Token is now stored in httpOnly cookie by backend
    // We rely on httpOnly cookie for authentication. Return response data for UI.
    return response.data;
  }

  // Set a token in memory (Authorization header) for the current session only.
  // This does NOT persist the token to localStorage and is safe for short-lived
  // development convenience. The server-side httpOnly cookie remains primary.
  setToken(token) {
    if (token) {
      this.api.defaults.headers['Authorization'] = `Bearer ${token}`;
    }
  }

  clearToken() {
    delete this.api.defaults.headers['Authorization'];
  }

  async verifyEmail(token) {
    const response = await this.api.get(`/auth/verify-email?token=${token}`);
    return response.data;
  }

  async getProfile() {
    const response = await this.api.get('/auth/profile');
    return response.data;
  }

  async logout() {
    try {
      await this.api.post('/auth/logout');
      // Cookies are cleared by backend; no local storage to clear since we avoid storing tokens in dev.
    } catch (error) {
      console.error('Logout API call failed:', error);
    }
  }

  async resendVerificationEmail(email) {
    const response = await this.api.post('/auth/resend-verification', email);
    return response.data;
  }

  async forgotPassword(email) {
    const response = await this.api.post('/auth/forgot-password', { email });
    return response.data;
  }

  async resetPassword(data) {
    const response = await this.api.post('/auth/reset-password', data);
    return response.data;
  }

  getToken() {
    // Token is now stored in httpOnly cookie, not accessible from JavaScript
    // We'll check authentication status via a server call or maintain a flag
    return null; // Cookies are not accessible from client-side JavaScript
  }

  async isAuthenticated() {
    try {
      // Check authentication by making a request to a protected endpoint
      await this.api.get('/auth/profile');
      return true;
    } catch (error) {
      return false;
    }
  }
}

export default new AuthService();
