/**
 * Services and business logic for the Cart domain.
 * @packageDocumentation
 */

import type {
  CartEntity,
  CartCreationData,
  CartUpdateData
} from '../entities/Cart';

import type {
  CartPort
} from '../ports/CartPort';

export class CartError extends Error {
  constructor(
    public code: string,
    message: string,
  ) {
    super(message);
    this.name = 'CartError';
  }
}

/**
 * Service implementation for Cart domain
 */
export class CartService {
  constructor(private readonly port: CartPort) {}

  /**
   * Get all cart entities
   */
  async getAll(): Promise<CartEntity[]> {
    try {
      return await this.port.getAll();
    } catch (error) {
      throw new CartError('GET_ALL_ERROR', 'Failed to get all cart entities');
    }
  }

  /**
   * Get a cart entity by ID
   */
  async getById(id: string): Promise<CartEntity> {
    try {
      return await this.port.getById(id);
    } catch (error) {
      throw new CartError('GET_BY_ID_ERROR', `Failed to get cart entity with id ${id}`);
    }
  }

  /**
   * Create a new cart entity
   */
  async create(data: CartCreationData): Promise<CartEntity> {
    try {
      return await this.port.create(data);
    } catch (error) {
      throw new CartError('CREATE_ERROR', 'Failed to create cart entity');
    }
  }

  /**
   * Update an existing cart entity
   */
  async update(id: string, data: CartUpdateData): Promise<CartEntity> {
    try {
      return await this.port.update(id, data);
    } catch (error) {
      throw new CartError('UPDATE_ERROR', `Failed to update cart entity with id ${id}`);
    }
  }

  /**
   * Delete a cart entity
   */
  async delete(id: string): Promise<void> {
    try {
      await this.port.delete(id);
    } catch (error) {
      throw new CartError('DELETE_ERROR', `Failed to delete cart entity with id ${id}`);
    }
  }
}
