import axios, { AxiosInstance } from 'axios'
import User, { HasInitials } from '../types/User'
import { Manager } from '@/types/Manager'

export class UserService {
  axios: AxiosInstance

  constructor(inst?: AxiosInstance) {
    this.axios =
      inst ??
      axios.create({
        withCredentials: true,
      })
  }

  loadUser(): Promise<User | Manager> {
    return this.axios.get('/api/user').then(response => response.data.user)
  }

  logout(): Promise<{ url: string }> {
    return this.axios
      .get('/logout')
      .then(response => ({ url: response.data.url }))
  }

  getUserInitials(user: HasInitials): string {
    return `${user.lastName ? user.lastName[0] : ''}${
      user.firstName ? user.firstName[0] : ''
    }`.toUpperCase()
  }

  getUserFullName(user: HasInitials): string {
    return `${user.lastName} ${user.firstName}`
  }
}

export default new UserService()
