import { useEffect } from 'react';
import { useAuth } from '../auth/AuthContext';
import { useIntegrations } from '../crm/hooks';
import { office365Api } from '../crm/api';
import api from '../api/client';


const SESSION_KEY = 'o365_profile_synced';

/**
 * Syncs the INSIGHT user profile from Microsoft 365 once per browser session.
 * Runs silently in the background — no UI feedback, no disruption on error.
 * Uses sessionStorage to prevent duplicate syncs within the same session.
 *
 * Fields overwritten where O365 has a non-null value:
 *   firstName, lastName, phone, mobile, city, street, postalCode
 */
export function useO365ProfileSync(): void {
  const { user, refreshUser } = useAuth();
  const { data: integrationsData } = useIntegrations();

  const isM365Connected =
    integrationsData?.data?.some(
      (i) => i.provider === 'MICROSOFT_365' && i.connected,
    ) ?? false;

  useEffect(() => {
    // Prerequisites: authenticated user + M365 connected + not yet synced this session
    if (!user || !isM365Connected) return;
    if (sessionStorage.getItem(SESSION_KEY)) return;

    // Mark as synced immediately to prevent duplicate calls on concurrent re-renders
    sessionStorage.setItem(SESSION_KEY, 'true');

    void (async () => {
      try {
        // Fetch profile + photo in parallel
        const [profileResult, photoResult] = await Promise.all([
          office365Api.getM365Profile(),
          office365Api.getM365Photo(),
        ]);
        const p = profileResult.data;

        // Build patch with all fields where O365 has a non-null value
        const patch: Record<string, string | null> = {};

        // Kontaktfelder
        if (p.givenName)           patch.firstName  = p.givenName;
        if (p.surname)             patch.lastName   = p.surname;
        if (p.businessPhones?.[0]) patch.phone      = p.businessPhones[0];
        if (p.mobilePhone)         patch.mobile     = p.mobilePhone;
        if (p.city)                patch.city       = p.city;
        if (p.streetAddress)       patch.street     = p.streetAddress;
        if (p.postalCode)          patch.postalCode = p.postalCode;

        // Organisationsfelder
        if (p.jobTitle)       patch.jobTitle       = p.jobTitle;
        if (p.department)     patch.department     = p.department;
        if (p.companyName)    patch.companyName    = p.companyName;
        if (p.officeLocation) patch.officeLocation = p.officeLocation;

        // Profilbild — nur wenn noch kein INSIGHT-Avatar gesetzt
        if (!user.avatar && photoResult.data.photoBase64) {
          patch.avatar = photoResult.data.photoBase64;
        }

        if (Object.keys(patch).length > 0) {
          await api.patch('/users/me', patch);
          await refreshUser();
        }
      } catch {
        // Silent failure — auto-sync must never disrupt the user experience.
        // Remove the flag so a future navigation attempt can retry.
        sessionStorage.removeItem(SESSION_KEY);
      }
    })();
    // refreshUser is stable from AuthContext; intentionally excluded from deps
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user?.id, isM365Connected]);
}
