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

class TasksApiHelper {
  private client = axios.create({
    baseURL: '/service/stpbroker/gateway',
  });

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

  async createTask(body: TaskItem) {
    const response = await this.client.post('/task', body);
    return response.data;
  }
}

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

const TasksService = {
  handler,
};

export { TasksService };

export interface TaskItem {
  metaClass?: string;
  impact?: string;
  topic?: string;
  description?: string;
  clientLogin?: string;
  clientName?: string;
  clientEmail?: string;
  clientPhone?: string;
  errorMessage?: string;
  processId?: string;
  processName?: string;
  taskName?: string;
}
