import { Navigate, useLocation } from 'react-router-dom';
import { Cookie } from './cookieClient';
import Swal from 'sweetalert2';
import { configureAuth } from './ReactQueryAuth';
import { loginWithUsernameAndPassword } from '../features/auth/api/login';
import { LoginFormValues } from '../features/auth/types/form';
import { getAuthUser } from '../features/auth/api/getAuthUser';
import { AuthUserResponse, UsersMeResponse } from '../features/auth/types/api';
import { paths } from '../config/paths';

async function handleUserResponse(data: AuthUserResponse): Promise<UsersMeResponse> {
    const { token, refresh_token, username, role } = data;
    Cookie.setAccessToken(token);
    Cookie.setRefreshToken(refresh_token);
    return { username, role };
}

async function userFn() {
    if (Cookie.getAccessToken() || Cookie.getRefreshToken()) {
        try {
            const data = await getAuthUser();
            return data;
        } catch (error) {
            Cookie.clearTokens();
        }
    }
    return null;
}

async function loginFn(dataForm: LoginFormValues): Promise<UsersMeResponse> {
    const response = await loginWithUsernameAndPassword(dataForm);
    const user = await handleUserResponse(response);
    return user;
}

async function logoutFn() {
    Cookie.clearTokens();
    return null;
}

const authConfig = {
    userFn,
    loginFn,
    logoutFn,
};

export const { useUser, useLogin, useLogout, AuthLoader } = configureAuth(authConfig);

export const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
    const user = useUser();
    const location = useLocation();

    if (!user.data) {
        return <Navigate to={paths.auth.login.getHref(location.pathname)} replace />;
    }

    return children;
};
