import {
  APIListUnpaginated,
  APIRetrieve,
  createExtendableAPI,
  useObjectFromStore,
} from '@rokoli/bnb/drf'
import { defineStore } from 'pinia'
import { computed, MaybeRefOrGetter, toRef } from 'vue'

import { createSteeringURL } from '@/api'
import { useI18n } from '@/i18n'
import { steeringAuthInit, useOnAuthBehaviour } from '@/stores/auth'
import { License } from '@/types'

type LicensedWork = {
  credits: string
  isUseExplicitlyGrantedByAuthor: boolean
}

export function useSelectedLicense(licenseId: MaybeRefOrGetter<License['id'] | null>) {
  const store = useLicenseStore()
  const { obj } = useObjectFromStore(licenseId, store)
  return obj
}

export function useLicenseValidator(
  license: MaybeRefOrGetter<License | null>,
  licensedWork: MaybeRefOrGetter<LicensedWork>,
) {
  const _license = toRef(license)
  const _licensedWork = toRef(licensedWork)
  const { t } = useI18n()
  const isUseExplicitlyGrantedByAuthorError = computed(() => {
    if (
      _license?.value?.requiresExpressPermissionForPublication &&
      !_licensedWork.value.isUseExplicitlyGrantedByAuthor
    ) {
      return { message: t('license.validation.requiresExpressPermissionForPublication') }
    }

    return undefined
  })
  const needsAuthorError = computed(() => {
    if (_license?.value?.needsAuthor && !_licensedWork.value.credits.trim()) {
      return { message: t('license.validation.requiresCredits') }
    }
    return undefined
  })
  const hasError = computed(
    () => isUseExplicitlyGrantedByAuthorError.value || needsAuthorError.value,
  )
  return { isUseExplicitlyGrantedByAuthorError, needsAuthorError, hasError }
}

export const useLicenseStore = defineStore('licenses', () => {
  const endpoint = createSteeringURL.prefix('licenses')
  const { api, base } = createExtendableAPI<License>(endpoint, steeringAuthInit)
  const listOperations = APIListUnpaginated(api)

  useOnAuthBehaviour(() => void listOperations.list())

  return {
    ...base,
    ...listOperations,
    ...APIRetrieve(api),
  }
})