/**
 * Authentication Service
 * Handles user authentication and token management
 */

import AsyncStorage from '@react-native-async-storage/async-storage';
import { ApiService } from './ApiService';

export const AuthService = {
  /**
   * Login user
   */
  login: async (username, password) => {
    try {
      const response = await ApiService.post('/auth', {
        username,
        password,
      });

      if (response.success && response.data) {
        // Store token and user data
        await AsyncStorage.setItem('auth_token', response.data.token);
        await AsyncStorage.setItem('user_data', JSON.stringify(response.data.user));
        await AsyncStorage.setItem('token_expires_at', response.data.expires_at);

        return {
          success: true,
          user: response.data.user,
          token: response.data.token,
        };
      }

      throw new Error(response.message || 'Login failed');
    } catch (error) {
      return {
        success: false,
        message: error.message || 'Login failed. Please try again.',
      };
    }
  },

  /**
   * Logout user
   */
  logout: async () => {
    try {
      await AsyncStorage.removeItem('auth_token');
      await AsyncStorage.removeItem('user_data');
      await AsyncStorage.removeItem('token_expires_at');
      return { success: true };
    } catch (error) {
      return { success: false, message: error.message };
    }
  },

  /**
   * Get current user
   */
  getCurrentUser: async () => {
    try {
      const userData = await AsyncStorage.getItem('user_data');
      if (userData) {
        return JSON.parse(userData);
      }
      return null;
    } catch (error) {
      return null;
    }
  },

  /**
   * Get auth token
   */
  getToken: async () => {
    try {
      return await AsyncStorage.getItem('auth_token');
    } catch (error) {
      return null;
    }
  },

  /**
   * Verify token is still valid
   */
  verifyToken: async (token) => {
    try {
      if (!token) return false;

      // Check if token is expired
      const expiresAt = await AsyncStorage.getItem('token_expires_at');
      if (expiresAt) {
        const expiryDate = new Date(expiresAt);
        if (expiryDate < new Date()) {
          return false;
        }
      }

      // Verify with API
      const response = await ApiService.get('/auth');
      return response.success === true;
    } catch (error) {
      return false;
    }
  },

  /**
   * Check if user is authenticated
   */
  isAuthenticated: async () => {
    try {
      const token = await AuthService.getToken();
      if (!token) return false;
      return await AuthService.verifyToken(token);
    } catch (error) {
      return false;
    }
  },
};
