import { PikkuFetch } from '@heygermany/sdk/pikku/pikku-fetch.gen.js'

const viteEnv = (import.meta as ImportMeta & {
    env?: Record<string, string | undefined>
}).env

const getBrowserApiBaseUrl = () => {
    if (typeof window === 'undefined') {
        return ''
    }

    const { hostname, origin } = window.location

    if (hostname === 'localhost' || hostname === '127.0.0.1') {
        return 'http://localhost:3000'
    }

    return origin
}

const getApiBaseUrl = () =>
    viteEnv?.VITE_API_BASE_URL ||
    process.env.VITE_API_BASE_URL ||
    process.env.API_URL ||
    getBrowserApiBaseUrl()

let client: PikkuFetch | null = null

const pikku = (): PikkuFetch => {
    if (!client) {
        client = new PikkuFetch({
            serverUrl: getApiBaseUrl(),
            credentials: 'include',
        })
    }
    return client
}

export { pikku }
