import PocketBase from 'pocketbase'

let _adminClient: PocketBase | null = null
let _tokenExpiry: number = 0

export async function getPBAdminClient(): Promise<PocketBase> {
  const config = useRuntimeConfig()
  const pbUrl = config.public.pocketbaseUrl as string

  if (!_adminClient) {
    _adminClient = new PocketBase(pbUrl)
  }

  // Re-authenticate if token expired (PB tokens last 7 days but refresh at 1h)
  if (!_adminClient.authStore.isValid || Date.now() > _tokenExpiry) {
    await _adminClient.collection('_superusers').authWithPassword(
      config.pbAdminEmail as string,
      config.pbAdminPassword as string
    )
    _tokenExpiry = Date.now() + 3600 * 1000 // 1 hour
  }

  return _adminClient
}
