import { defineStore } from "pinia"
import { ref } from "vue"
import { request } from "@/scripts/request"
import { Preferences } from "@capacitor/preferences"

export interface Userinfo {
  isReady: boolean
  isLoggedIn: boolean
  displayName: string
  data: any
}

const defaultUserinfo: Userinfo = {
  isReady: false,
  isLoggedIn: false,
  displayName: "Citizen",
  data: null
}

export async function getAtk() {
  return (await Preferences.get({ key: "identity.access_token" })).value
}

export async function getRtk() {
  return (await Preferences.get({ key: "identity.refresh_token" })).value
}

export async function checkLoggedIn(): Promise<boolean> {
  return (await Preferences.get({ key: "identity.access_token" })).value != null
}

export const useUserinfo = defineStore("userinfo", () => {
  const userinfo = ref(defaultUserinfo)
  const isReady = ref(false)

  async function readProfiles() {
    if (!(await checkLoggedIn())) {
      isReady.value = true
    }

    const res = await request("identity", "/api/users/me", {
      headers: { Authorization: `Bearer ${await getAtk()}` }
    })

    if (res.status !== 200) {
      return
    }

    const data = await res.json()

    userinfo.value = {
      isReady: true,
      isLoggedIn: true,
      displayName: data["nick"],
      data: data
    }
  }

  return { userinfo, isReady, readProfiles }
})
