import axios from 'axios';
import store from '@/state/store';
import Vue from 'vue';

class TicketsApiHelper {
  private client = axios.create({
    baseURL: `${Vue.prototype.$appConfig.PREORDER_SERVICE}`,
  });

  constructor(accessToken?: string) {
    if (accessToken) {
      this.client.defaults.headers.Authorization = `Bearer ${accessToken}`;
    }
  }

  async ticketFind(searchParams: TicketFindRequestParams) {
    const response = await this.client.post('/ticket/find', searchParams);
    return response.data;
  }

  async ticketGet(bookId: string) {
    const response = await this.client.get(`/ticket/get/${bookId}`);
    return response.data;
  }

  async ticketUpdateStatus(body: { bookId: string; statusCode: string }) {
    const response = await this.client.post('/ticket/updateStatus/', body);
    return response.data;
  }
}

const handler = ({ useAuth = true }): Promise<TicketsApiHelper> => {
  return new Promise((resolve, reject) => {
    if (useAuth) {
      store
        .dispatch('oidcClient/getAccessToken')
        .then((accessToken) => {
          resolve(new TicketsApiHelper(accessToken));
        })
        .catch((e) => {
          reject(e);
        });
    } else {
      resolve(new TicketsApiHelper());
    }
  });
};

const TicketsService = {
  handler,
};

export { TicketsService };

export interface TicketFindRequestParams {
  org?: string;
  employee?: string;
  service?: string;
  startDate?: string;
  endDate?: string;
}
