import { getAtk, getRtk } from "@/stores/userinfo"
import { Preferences } from "@capacitor/preferences"

const serviceMap: { [id: string]: string } = {
  interactive: "https://co.solsynth.dev",
  identity: "https://id.solsynth.dev"
}

export async function request(service: string, input: string, init?: RequestInit, noRetry?: boolean) {
  const url = buildRequestUrl(service, input)
  const res = await fetch(url, init)

  if (res.status === 401 && !noRetry) {
    const res = await request("identity", "/api/auth/token", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        refresh_token: await getRtk(),
        grant_type: "refresh_token"
      })
    }, true)
    if (res.status !== 200) {
      const err = await res.text()
      throw new Error(err)
    } else {
      const data = await res.json()
      await Preferences.set({
        key: "identity.access_token",
        value: data["access_token"]
      })
      await Preferences.set({
        key: "identity.refresh_token",
        value: data["refresh_token"]
      })
    }

    console.info("[REQUEST] Auth context has been refreshed.")
    return await request(service, input, Object.assign(init as any, {
      headers: { Authorization: `Bearer ${await getAtk()}` }
    }), true)
  }

  return res
}

export function buildRequestUrl(service: string, input: string) {
  const prefix = serviceMap[service] ?? ""
  return prefix + input
}
