import { BaseEndpoint } from '../base';
import { AppStatusRequest, GetLatestAppStatusRequest, AppStatusOverview } from './types';
import { InvalidRequestError, AuthenticationError, ServerError } from '../../errors';

export class AppEndpoint extends BaseEndpoint {
  constructor(client: any) {
    super(client, '/api/app');
  }

  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');
    }
  }

  /**
   * Update the status of an app
   * @param data - The request parameters
   * @returns Promise with the app status overview
   * @throws {InvalidRequestError} If required fields are missing or invalid
   * @throws {AuthenticationError} If API keys are invalid
   * @throws {ServerError} If server encounters an error
   */
  async updateStatus(data: AppStatusRequest): Promise<AppStatusOverview> {
    this.validateRequiredKeys(data);

    try {
      return await this.post<AppStatusOverview>('/status', 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;
    }
  }

  /**
   * Get the latest status of an app
   * @param data - The request parameters
   * @returns Promise with the app status overview
   * @throws {InvalidRequestError} If required fields are missing or invalid
   * @throws {AuthenticationError} If API keys are invalid
   * @throws {ServerError} If server encounters an error
   */
  async getLatestStatus(data: GetLatestAppStatusRequest): Promise<AppStatusOverview> {
    this.validateRequiredKeys(data);

    try {
      return await this.get<AppStatusOverview>('/status/latest', { 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;
    }
  }
} 