import Cookies from 'js-cookie';
import { $api } from '@/api/api';
import { setJSessionID } from '@/utils/setCookie';

export interface ILoginForm {
  account: string;
  password: string;
}

type ILoginResponse =
  | {
      JSESSIONID: string;
      account_name: string;
      jsession: string;
      result: 0;
    }
  | {
      message: string;
      result: 1;
    };

export const AuthorizationService = {
  async login(body: ILoginForm) {
    const StandartRes = await $api.get('/StandardApiAction_login.action', {
      params: body,
    }).then((res) => res.data as ILoginResponse);

    const formData = new FormData();
    formData.set('account', body.account.toLowerCase());
    formData.set('ipson', btoa(body.password));
    formData.set('language', 'ru');
    formData.set('v9OldStyle', '');

    await $api.post<any>('/StandardLoginAction_login.action', formData).then(async (res) => {
      if (res.data.JSESSIONID) {
        // JSESSIONID - кука для хранения информации о сессии прокси
        await setJSessionID(res.data.JSESSIONID)
      }
    });

    return StandartRes;
  },

  async logout() {
    return $api.get('/StandardApiAction_logout.action?jsession');
  },
};
