/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { Buffer } from 'buffer'
import { useEffect } from 'react'

function loginUrl(callbackUrl: string) {
    let params = new URLSearchParams()
    params.set('return_sso_url', callbackUrl)
    const payload = Buffer.from(params.toString()).toString('base64')
    const url = new URL('https://accounts.moecube.com/signin')
    params = url['searchParams']
    params.set('sso', payload)
    return url.toString()
}

interface MyCardSSOUser {
    id: string
    username: string
    name: string
    email: string
    password_hash: string
    salt: string
    active: string
    admin: string
    avatar: string
    locale: string
    registration_ip_address: string
    ip_address: string
    created_at: string
    updated_at: string
    return_sso_url: string
    external_id: string
    avatar_url: string
    avatar_force_update: string
    token: string
}

export class MyCard {
    user: MyCardSSOUser
    isActive: boolean
    constructor() {
        if (!process.env.NEXT_PUBLIC_MYCARD) {
            this.isActive = false
            return
        }
        this.isActive = true
        if (typeof window === 'undefined') {
            return
        }
        const ssoString = new URLSearchParams(window.location.search).get('sso')
        const loginString = ssoString || window.localStorage.getItem('mycardLogin')
        if (!loginString) {
            return
        }
        window.localStorage.setItem('mycardLogin', loginString)
        const decodedLoginString = Buffer.from(loginString, 'base64').toString()
        const params = new URLSearchParams(decodedLoginString)
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        this.user = Object.fromEntries(params)
    }

    login() {
        if (typeof window === 'undefined') {
            return
        }
        const currentUrl = window.location.href
        window.location.replace(loginUrl(currentUrl))
    }

    getToken() {
        if (!this.user) {
            if (this.isActive) {
                this.login()
            }
            return ''
        }
        return this.user.token
    }

    logout() {
        window.localStorage.removeItem('mycardLogin')
        this.login()
    }
}

export const mycard = new MyCard()
