import { UserFactory } from './factories/userFactory.js'

export const userService = {
  async getMe() {
    const { $pb } = useNuxtApp()
    if (!$pb.authStore.isValid) return null
    const record = await $pb.collection('users').getOne($pb.authStore.model.id)
    return UserFactory.fromApiUser(record)
  },

  async login(email, password) {
    const { $pb } = useNuxtApp()
    const authData = await $pb.collection('users').authWithPassword(email, password)
    return UserFactory.fromApiUser({ ...authData.record, token: authData.token })
  },

  async logout() {
    const { $pb } = useNuxtApp()
    $pb.authStore.clear()
  },

  async register(email, password, name) {
    const { $pb } = useNuxtApp()
    await $pb.collection('users').create({
      email,
      password,
      passwordConfirm: password,
      name,
    })
    const authData = await $pb.collection('users').authWithPassword(email, password)
    return UserFactory.fromApiUser({ ...authData.record, token: authData.token })
  },

  /**
   * Return the current PocketBase auth token (JWT).
   * The upload service sends this as a Bearer token to the FastAPI backend.
   */
  getToken() {
    const { $pb } = useNuxtApp()
    return $pb.authStore.isValid ? $pb.authStore.token : null
  },
}
