import type { CartEntity, CartCreationData, CartUpdateData } from '../entities/Cart';
import type { CartPort } from '../ports/CartPort';
import { CartError } from '../services/CartService';
import { httpClient } from '../../../lib/http-client';

/**
 * HTTP Adapter implementation for Cart domain
 */
export class CartAdapter implements CartPort {
  private readonly endpoint = '/cart';

  async getAll(): Promise<CartEntity[]> {
    try {
      const response = await httpClient.get<CartEntity[]>(this.endpoint);
      return response.data;
    } catch (error) {
      throw new CartError('REQUEST_ERROR', `Failed to fetch cart list`);
    }
  }

  async getById(id: string): Promise<CartEntity> {
    try {
      const response = await httpClient.get<CartEntity>(`${this.endpoint}/${id}`);
      return response.data;
    } catch (error) {
      throw new CartError('REQUEST_ERROR', `Failed to fetch cart with id ${id}`);
    }
  }

  async create(data: CartCreationData): Promise<CartEntity> {
    try {
      const response = await httpClient.post<CartEntity>(this.endpoint, data);
      return response.data;
    } catch (error) {
      throw new CartError('REQUEST_ERROR', `Failed to create cart`);
    }
  }

  async update(id: string, data: CartUpdateData): Promise<CartEntity> {
    try {
      const response = await httpClient.put<CartEntity>(`${this.endpoint}/${id}`, data);
      return response.data;
    } catch (error) {
      throw new CartError('REQUEST_ERROR', `Failed to update cart with id ${id}`);
    }
  }

  async delete(id: string): Promise<void> {
    try {
      await httpClient.delete(`${this.endpoint}/${id}`);
    } catch (error) {
      throw new CartError('REQUEST_ERROR', `Failed to delete cart with id ${id}`);
    }
  }
}