import { CartItem } from '@/types/cart';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL ;

export interface ApiCartItem {
  id: string;
  quantity: number;
  product_variant_id: string;
  product: {
    id: string;
    title: string;
    slug: string;
    price: number;
    image_src: string;
    description: string;
  };
  variant: {
    id: string;
    size: string;
    color: string;
    price: number;
    stock: number;
    sku: string;
  };
  subtotal: number;
}

export interface ApiCartResponse {
  items: ApiCartItem[];
  total_items: number;
  total_price: number;
}

class CartService {
  private getAuthToken(): string | null {
    if (typeof window === 'undefined') return null;
    return localStorage.getItem('auth_token');
  }

  private getHeaders(): HeadersInit {
    const token = this.getAuthToken();
    console.log('CartService getAuthToken:', token ? 'Token found' : 'No token found');
    const headers: HeadersInit = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    };
    
    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
      console.log('Added Authorization header to request');
    } else {
      console.log('No token found, sending request without Authorization header');
    }
    
    console.log('Request headers:', headers);
    return headers;
  }

  async getCart(): Promise<ApiCartResponse> {
    console.log('CartService.getCart called');
    const response = await fetch(`${API_BASE_URL}/cart`, {
      method: 'GET',
      headers: this.getHeaders(),
    });

    if (!response.ok) {
      console.error('Failed to fetch cart:', response.status, response.statusText);
      throw new Error(`Failed to fetch cart: ${response.statusText}`);
    }

    const data = await response.json();
    console.log('Raw API response:', data);
    return data;
  }

  async addToCart(productId: string, quantity: number = 1): Promise<{ message: string; cart_item?: ApiCartItem; guest_cart_item?: ApiCartItem }> {
    const response = await fetch(`${API_BASE_URL}/cart/add`, {
      method: 'POST',
      headers: this.getHeaders(),
      body: JSON.stringify({
        product_id: productId,
        quantity,
      }),
    });

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({ error: response.statusText }));
      throw new Error(errorData.error || `Failed to add item to cart: ${response.statusText}`);
    }

    return await response.json();
  }

  async updateCartItem(cartItemId: string, quantity: number): Promise<{ message: string; cart_item: ApiCartItem }> {
    const response = await fetch(`${API_BASE_URL}/cart/${cartItemId}`, {
      method: 'PATCH',
      headers: this.getHeaders(),
      body: JSON.stringify({
        quantity,
      }),
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.error || `Failed to update cart item: ${response.statusText}`);
    }

    return await response.json();
  }

  async removeFromCart(cartItemId: string): Promise<{ message: string }> {
    const response = await fetch(`${API_BASE_URL}/cart/${cartItemId}`, {
      method: 'DELETE',
      headers: this.getHeaders(),
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.error || `Failed to remove item from cart: ${response.statusText}`);
    }

    return await response.json();
  }

  async clearCart(): Promise<{ message: string }> {
    const response = await fetch(`${API_BASE_URL}/cart/clear`, {
      method: 'DELETE',
      headers: this.getHeaders(),
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.error || `Failed to clear cart: ${response.statusText}`);
    }

    return await response.json();
  }

  // Convert API cart item to frontend cart item format
  convertApiItemToCartItem(apiItem: ApiCartItem): CartItem {
    console.log('Converting API item:', apiItem);
    const cartItem = {
      id: apiItem.id,
      productId: apiItem.product.id,
      title: apiItem.product.title,
      price: apiItem.product.price,
      imageSrc: apiItem.product.image_src,
      quantity: apiItem.quantity,
      slug: apiItem.product.slug,
    };
    console.log('Converted cart item:', cartItem);
    return cartItem;
  }

  // Convert API cart response to frontend cart format
  convertApiCartToCart(apiCart: ApiCartResponse): {
    items: CartItem[];
    totalItems: number;
    totalPrice: number;
  } {
    console.log('Converting API cart response:', apiCart);
    const result = {
      items: apiCart.items.map(item => this.convertApiItemToCartItem(item)),
      totalItems: apiCart.total_items,
      totalPrice: apiCart.total_price,
    };
    console.log('Converted cart result:', result);
    return result;
  }
}

export const cartService = new CartService();