/**
 * Organization/Team composable wrapper
 *
 * This composable provides organization/team functionality when enabled via
 * saas.enableOrganizations config. If organizations are disabled, it returns
 * a minimal interface that works with user-scoped operations.
 *
 * Usage in extending apps:
 *
 * With organizations enabled:
 * const { currentOrg, organizations } = useOrganization()
 *
 * Without organizations:
 * const { currentOrg } = useOrganization()
 * // currentOrg will be a user-based fallback organization
 */

export interface Organization {
  id: string
  name: string
  slug?: string
  logo?: string | null
  createdAt?: Date
  metadata?: Record<string, unknown>
}

export function useOrganization() {
  const config = useRuntimeConfig()
  const { user } = useAuth()
  const enableOrganizations = config.public.saas?.enableOrganizations ?? false

  // For when organizations are disabled, create a fallback "personal" organization
  const fallbackOrganization = computed<Organization | null>(() => {
    if (!user.value) return null

    return {
      id: user.value.id,
      name: user.value.name || user.value.email,
      slug: user.value.id,
      logo: user.value.image,
      createdAt: user.value.createdAt,
      metadata: {}
    }
  })

  if (!enableOrganizations) {
    // Return a simplified interface when organizations are disabled
    return {
      currentOrg: fallbackOrganization,
      organizations: computed(() => fallbackOrganization.value ? [fallbackOrganization.value] : []),
      isEnabled: false
    }
  }

  // When organizations are enabled, use Better Auth's organization functionality
  // This requires the organizationClient plugin to be loaded
  const organizations = useState<Organization[]>('organizations', () => [])
  const currentOrg = useState<Organization | null>('currentOrganization', () => null)

  // Fetch organizations on mount (client-side only)
  if (import.meta.client && user.value) {
    // TODO: Implement Better Auth organization fetching
    // This would use the organizationClient plugin methods
    // For now, we'll use the fallback until full implementation
    currentOrg.value = fallbackOrganization.value
    organizations.value = fallbackOrganization.value ? [fallbackOrganization.value] : []
  }

  return {
    currentOrg,
    organizations,
    isEnabled: true
  }
}
