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

import type {
  PaymentEntity,
  PaymentCreationData,
  PaymentUpdateData
} from '../entities/Payment';

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

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

/**
 * Service implementation for Payment domain
 */
export class PaymentService {
  constructor(private readonly port: PaymentPort) {}

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

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

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

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

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