import {createRemoteJWKSet, jwtVerify} from 'jose';
import {Api as Auth} from '../client/auth_client';
import {useNavigate} from "react-router-dom";

export interface TokenPayload {
    unique_name: string;
    exp: number;
    [key: string]: any;
}

export const validateToken = async (token: string): Promise<TokenPayload | null> => {
    try {
        const JWKS = createRemoteJWKSet(
            new URL('auth/.well-known/jwks', window.location.origin)
        );
        const { payload } = await jwtVerify(token, JWKS);
        const tokenPayload = payload as TokenPayload;
        const currentTime = Math.floor(Date.now() / 1000);

        if (tokenPayload.exp && tokenPayload.exp > currentTime) {
            return tokenPayload;
        } else {
            return null;
        }
    } catch (error) {
        console.error('Token validation failed', error);
        return null;
    }
};

export const handleLogout = async (navigate: ReturnType<typeof useNavigate>) => {
    const token = localStorage.getItem('authToken');
    if (token) {
        const client = new Auth({
            baseUrl: 'auth',
            securityWorker: () => ({ headers: { Authorization: `Bearer ${token}` } }),
        });

        try {
            const result = await client.logOut.logOutList();
            if (result?.data?.logOutSuccess) {
                localStorage.removeItem('authToken');
                navigate('/login');
            }
        } catch (error) {
            console.error('Logout failed', error);
        }
    } else {
        navigate('/login');
    }
};

export const GetUserPrivileges = async (navigate: ReturnType<typeof useNavigate>) => {
    const token = localStorage.getItem('authToken');
    if (token) {
        const client = new Auth({
            baseUrl: 'auth',
            securityWorker: () => ({ headers: { Authorization: `Bearer ${token}` } }),
        });

        try {
            const result = await client.privilege.getUserPrivilegeCreate();
            return result.data;
        } catch (error) {
            localStorage.removeItem('authToken');
            navigate('/login');
        }
    } else {
        navigate('/login');
    }
};

export const UnAuthorized = async (navigate: ReturnType<typeof useNavigate>) => {
    localStorage.removeItem('authToken');
    navigate('/login');
};

