import { Authorize } from "../types/index";
import { useServerSdk } from "../../hooks/index";

export class H5Authorize extends Authorize {
    async checkLogin(): Promise<boolean> {
        // 检查URL中是否有OAuth回调参数
        const urlParams = new URLSearchParams(window.location.search);
        const accessToken = urlParams.get('access_token');
        const userId = urlParams.get('user_id');
        if (accessToken && userId) {
            // 处理OAuth回调
            try {
                const serverSdk = useServerSdk();
                serverSdk.setAccessToken(accessToken, userId);

                // 清理URL参数，避免重复处理
                const newUrl = window.location.pathname;
                window.history.replaceState(null, '', newUrl);

                console.log('OAuth登录成功，token已保存');
                return true;
            } catch (error) {
                console.error('处理OAuth回调失败:', error);
                return false;
            }
        }

        // 如果没有回调参数，检查本地存储的token
        try {
            const serverSdk = useServerSdk();
            const profile = await serverSdk.profile();
            return !!profile;
        } catch (error) {
            console.log('本地token无效或已过期');
            return false;
        }
    }

    async login(): Promise<void> {
        const { hostname, protocol, port } = window.location;
        let baseUrl = `${protocol}//${hostname}`
        if (hostname === 'localhost') {
            baseUrl = `${protocol}//${hostname}:${port}`
        }
        window.location.href = `https://mixvideo-workflow.bowong.cc/auth/google/authorize?redirect_url=${baseUrl}`
    }
}