import { warnOnce } from '../core/app-dom.js';

const switchTenant = async (link) => {
  const tenantId = link.dataset.switchTenant;
  const csrfKey = link.dataset.csrfKey;
  const csrfToken = link.dataset.csrfToken;
  const errorMessage = link.dataset.errorMessage || 'Failed to switch tenant';

  if (!tenantId || !csrfKey || !csrfToken) {
    warnOnce('UI_DATA_MISSING', 'Missing tenant ID or CSRF token', { module: 'tenant-switcher' });
    return;
  }

  // Disable link during request
  link.style.pointerEvents = 'none';
  link.style.opacity = '0.5';

  try {
    const body = new URLSearchParams({
      tenant_id: tenantId,
      [csrfKey]: csrfToken
    });

    const response = await fetch('admin/users/switch-tenant', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json',
        'X-Requested-With': 'fetch'
      },
      body
    });

    if (response.ok) {
      const data = await response.json();
      if (data.ok) {
        window.location.reload();
      } else {
        warnOnce('FETCH_FAILED', 'Tenant switch failed', { module: 'tenant-switcher', error: data.error });
        alert(errorMessage);
        link.style.pointerEvents = '';
        link.style.opacity = '';
      }
    } else {
      warnOnce('FETCH_FAILED', `Tenant switch server error: ${response.status}`, { module: 'tenant-switcher' });
      alert(errorMessage);
      link.style.pointerEvents = '';
      link.style.opacity = '';
    }
  } catch (error) {
    warnOnce('FETCH_ERROR', 'Tenant switch network error', { module: 'tenant-switcher', error });
    alert(errorMessage);
    link.style.pointerEvents = '';
    link.style.opacity = '';
  }
};

const initTenantSwitcher = () => {
  const tenantLinks = document.querySelectorAll('[data-switch-tenant]');
  if (!tenantLinks.length) {
    warnOnce('UI_EL_MISSING', 'Missing tenant switch links', { module: 'tenant-switcher' });
    return;
  }

  tenantLinks.forEach(link => {
    link.addEventListener('click', (e) => {
      e.preventDefault();
      switchTenant(link);
    });
  });
};

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initTenantSwitcher);
} else {
  initTenantSwitcher();
}
