'use client';

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

import { setSession } from './utils';
import { STORAGE_KEY, REFRESH_STORAGE_KEY } from './constant';

/** **************************************
 * Sign in
 *************************************** */
export const signInWithPassword = async ({ email, password }) => {
  try {
    const res = await axios.post(endpoints.auth.signIn, { email, password });

    const data = res.data?.data;
    const accessToken = data?.tokens?.access;
    const refreshToken = data?.tokens?.refresh;

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

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

/** **************************************
 * Sign up
 *************************************** */
export const signUp = async ({ email, password, passwordConfirm, firstName, lastName, role, city, timezone }) => {
  try {
    const params = {
      email,
      password,
      password_confirm: passwordConfirm,
      first_name: firstName,
      last_name: lastName,
      role: role || 'client',
      city: city || '',
      timezone: timezone || (typeof Intl !== 'undefined' ? Intl.DateTimeFormat().resolvedOptions().timeZone : 'Europe/Moscow'),
    };

    const res = await axios.post(endpoints.auth.signUp, params);

    const data = res.data?.data;
    const accessToken = data?.tokens?.access;
    const refreshToken = data?.tokens?.refresh;

    if (!accessToken) {
      // Регистрация прошла, но токен не выдан (требуется верификация email)
      return { requiresVerification: true };
    }

    await setSession(accessToken, refreshToken);
    return { requiresVerification: false };
  } catch (error) {
    console.error('Error during sign up:', error);
    throw error;
  }
};

/** **************************************
 * Sign out
 *************************************** */
export const signOut = async () => {
  try {
    await setSession(null);
  } catch (error) {
    console.error('Error during sign out:', error);
    throw error;
  }
};

/** **************************************
 * Refresh token
 *************************************** */
export const refreshAccessToken = async () => {
  try {
    const refreshToken = localStorage.getItem(REFRESH_STORAGE_KEY);
    if (!refreshToken) throw new Error('No refresh token');

    const res = await axios.post(endpoints.auth.refresh, { refresh: refreshToken }, {
      headers: { Authorization: undefined },
    });

    const accessToken = res.data?.access;
    if (!accessToken) throw new Error('No access token in refresh response');

    await setSession(accessToken, refreshToken);
    return accessToken;
  } catch (error) {
    console.error('Error during token refresh:', error);
    throw error;
  }
};

/** **************************************
 * Request password reset
 *************************************** */
export const requestPasswordReset = async ({ email }) => {
  try {
    await axios.post(endpoints.auth.passwordReset, { email });
  } catch (error) {
    console.error('Error during password reset request:', error);
    throw error;
  }
};

/** **************************************
 * Confirm password reset
 *************************************** */
export const confirmPasswordReset = async ({ token, newPassword, newPasswordConfirm }) => {
  try {
    await axios.post(endpoints.auth.passwordResetConfirm, {
      token,
      new_password: newPassword,
      new_password_confirm: newPasswordConfirm,
    });
  } catch (error) {
    console.error('Error during password reset confirm:', error);
    throw error;
  }
};

/** **************************************
 * Verify email
 *************************************** */
export const verifyEmail = async ({ token }) => {
  try {
    const res = await axios.post(endpoints.auth.verifyEmail, { token });
    return res.data;
  } catch (error) {
    console.error('Error during email verification:', error);
    throw error;
  }
};
