import { BaseEndpoint } from '../base';
import { ListItemsRequest, ListItemsResponse } from './types';
import { InvalidRequestError, AuthenticationError, ServerError } from '../../errors';

export class ItemsEndpoint extends BaseEndpoint {
  constructor(client: any) {
    super(client, '/api/items');
  }

  private validateRequiredKeys(data: { organization_apikey?: string; app_apikey?: string }) {
    if (!data.organization_apikey) {
      throw new InvalidRequestError('organization_apikey is required');
    }
    if (!data.app_apikey) {
      throw new InvalidRequestError('app_apikey is required');
    }
  }

  /**
   * List all items for an app/tenant
   * @param data - The list items request parameters
   * @returns Promise with the list items response
   * @throws {InvalidRequestError} If required fields are missing
   * @throws {AuthenticationError} If API keys are invalid
   * @throws {ServerError} If server encounters an error
   */
  async listItems(data: ListItemsRequest): Promise<ListItemsResponse> {
    this.validateRequiredKeys(data);

    try {
      return await this.get<ListItemsResponse>('', { params: data });
    } catch (error: any) {
      if (error.response?.status === 400) {
        throw new InvalidRequestError(error.response.data?.message || 'Invalid request');
      }
      if (error.response?.status === 401) {
        throw new AuthenticationError('Invalid API keys');
      }
      if (error.response?.status === 500) {
        throw new ServerError('Internal server error');
      }
      throw error;
    }
  }
} 