/**
 * Database service for frontend
 * 
 * This service provides an interface for frontend code to make database
 * operations via API calls instead of directly using Prisma in the browser
 */

import { API_BASE_URL } from '../config/apiConfig';

// API endpoints
const API_ENDPOINTS = {
  LOGIN: '/api/login',
  USERS: '/api/users',
};

/**
 * User authentication service
 */
export const authApi = {
  /**
   * Authenticate a user with email and password
   */
  login: async (email: string, hashedPassword: string) => {
    try {
      const response = await fetch(`${API_BASE_URL}${API_ENDPOINTS.LOGIN}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Requested-With': 'XMLHttpRequest',
        },
        body: JSON.stringify({ email, password: hashedPassword }),
        credentials: 'include',
      });

      return await response.json();
    } catch (error) {
      console.error('Login error:', error);
      return {
        success: false,
        error: 'Failed to connect to authentication service'
      };
    }
  },
};

/**
 * User management service
 */
export const usersApi = {
  /**
   * Get user by email
   */
  getUserByEmail: async (email: string, token: string) => {
    try {
      const response = await fetch(`${API_BASE_URL}${API_ENDPOINTS.USERS}?email=${encodeURIComponent(email)}`, {
        headers: {
          'Authorization': `Bearer ${token}`,
          'X-Requested-With': 'XMLHttpRequest',
        },
      });
      
      return await response.json();
    } catch (error) {
      console.error('Get user error:', error);
      return { success: false, error: 'Failed to fetch user data' };
    }
  },
};