import { AxiosInstance } from 'axios'

import { HealthStatus, IdParam } from '../common/types'
import { Offer } from './types'

/**
 * Service class for orderbook API calls. Requires an organizer to be set (call to `useOrganizer`)
 */
export class OrderbookService {
	constructor(readonly client: AxiosInstance, readonly version: string) { }

	/**
	 * Returns true if the service is reachable
	 * Currently the
	 *
	 * @returns Services' online status
	 */
	async health(): Promise<HealthStatus> {
		try {
			const res = await this.client.get(`orderbook/health`)
			if (res.data.status === 'ok') {
				return { online: true }
			}
		} catch (e) {
			// Do nothing
		}

		return { online: false }
	}

	/**
	 * Returns all offers which belong to the current user
	 *
	 * @returns 
	 */
	async getMine(): Promise<Offer[]> {
		const res = await this.client.get(`orderbook/${this.version}/offer/mine`)

		return res.data.data
	}

	/**
	 * Delete the given offer from the orderbook
	 *
	 * @param offerId 
	 */
	async deleteOffer(offerId: IdParam): Promise<void> {
		await this.client.delete(`orderbook/${this.version}/offer/${offerId.id}`)
	}
}
