import { ref } from 'vue'
import Swal from 'sweetalert2'
import { getApiErrorMessage } from '@/core/utils/getApiErrorMessage'
import { launchExternalSystemSso } from '../services/external-system.service'
import { isExternalSystemAccessible } from '../utils/external-system.utils'
import type { ExternalSystem } from '../types/external-system.types'

export function useExternalSystemLaunch() {
  const launching = ref(false)

  async function launchExternalSystem(system: ExternalSystem) {
    if (!isExternalSystemAccessible(system) || launching.value) {
      return
    }

    launching.value = true

    try {
      if (system.sso_enabled) {
        const response = await launchExternalSystemSso(system.code)
        window.open(
          response.data.launch_url,
          system.opens_in_new_tab ? '_blank' : '_self',
          'noopener,noreferrer',
        )
        return
      }

      window.open(
        system.url,
        system.opens_in_new_tab ? '_blank' : '_self',
        'noopener,noreferrer',
      )
    } catch (error) {
      await Swal.fire({
        icon: 'error',
        title: 'Gagal membuka sistem',
        text: getApiErrorMessage(error, 'Tidak dapat membuka sistem luaran.'),
      })
    } finally {
      launching.value = false
    }
  }

  return {
    launching,
    launchExternalSystem,
  }
}
