import { ref } from 'vue'
import { Notify } from 'quasar'
import { usePermissions } from './usePermissions'

export function useLegacySync ({ loadPerms, loadGroupMembers, selectedGroup } = {}) {
  const { HUB_URL } = usePermissions()

  const legacySyncing = ref(false)
  const showSyncDialog = ref(false)
  const syncResult = ref(null)

  async function syncLegacy (dryRun = true) {
    legacySyncing.value = true
    try {
      const res = await fetch(HUB_URL + '/auth/sync-legacy', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ dry_run: dryRun }),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error || 'Sync failed')
      syncResult.value = data
      showSyncDialog.value = true
      if (!dryRun && data.summary.to_sync > 0) {
        Notify.create({ type: 'positive', message: `${data.summary.to_sync} utilisateurs synchronises`, timeout: 3000 })
        if (loadPerms) await loadPerms()
        if (selectedGroup?.value && loadGroupMembers) await loadGroupMembers(selectedGroup.value)
      }
    } catch (e) {
      Notify.create({ type: 'negative', message: 'Erreur sync legacy: ' + e.message, timeout: 4000 })
    } finally {
      legacySyncing.value = false
    }
  }

  return { legacySyncing, showSyncDialog, syncResult, syncLegacy }
}
