import { ServiceBase } from '@/services/ServiceBase'
import { useAuthStore } from '@/stores/auth'
import { storeToRefs } from 'pinia'
import { NetworkService } from '@/services/NetworkService'

export class AuthenticationService extends ServiceBase {
  private apiUrl = import.meta.env.VITE_API_URL
  private networkService = new NetworkService()

  isAuthenticated() {
    const auth = useAuthStore()
    const { isLoggedIn } = storeToRefs(auth)
    return isLoggedIn
  }

  async login(username: string, password: string) {
    try {
      const res = await this.networkService.post({
        uri: '/login',
        body: { username, password }
      })
      const { token } = res
      this.persist(token)
      return token
    } catch (error) {
      console.error(error)
    }
  }

  async logout() {
    const auth = useAuthStore()
    const { setJwt, setUser } = auth
    setJwt(undefined)
    setUser(undefined)
    sessionStorage.removeItem('token')
  }

  private persist(jwt: string) {
    const auth = useAuthStore()
    const { setJwt, setUser } = auth
    const loggedUser = this.parseJwt(jwt)
    setJwt(jwt)
    setUser(loggedUser)
    sessionStorage.setItem('token', jwt)
  }

  private parseJwt(token: string) {
    if (!token) {
      return
    }
    const base64Url = token.split('.')[1] ?? ''
    const base64 = base64Url.replace('-', '+').replace('_', '/')
    return JSON.parse(window.atob(base64))
  }

  hasRoles(rolesToCheck: string[]) {
    const auth = useAuthStore()
    const { roles } = storeToRefs(auth)
    return roles.value.some((role) => rolesToCheck.includes(role))
  }
}
