'use client';

import { paths } from 'src/routes/paths';

import axios, { endpoints } from 'src/utils/axios';

import { GATEWAY_API_URL } from 'src/config-global';

import { setSession } from './utils';

// ----------------------------------------------------------------------

export type SignInParams = {
  username: string;
  password: string;
};

/** **************************************
 * Sign in
 *************************************** */
export const signInWithPassword = async ({ username, password }: SignInParams): Promise<void> => {
  try {
    const params = { username, password };
    const res = await axios.post(`${GATEWAY_API_URL}${endpoints.auth.login}`, params);
    const { token } = res.data;

    if (!token) {
      throw new Error('Access token not found in response');
    }

    setSession(token);
  } catch (error) {
    console.error('Error during sign in:', error);
    throw error;
  }
};

/** **************************************
 * Sign out
 *************************************** */
export const signOut = async (): Promise<void> => {
  try {
    setSession(null);
    window.location.href = paths.auth.jwt.signIn;
  } catch (error) {
    console.error('Error during sign out:', error);
    throw error;
  }
};
