import { hasStoredClientSession } from '$lib/session';
import { api } from '$lib/api';
import type { XeroContact, XeroContactLinkRow, XeroStatus } from '$lib/types';

// Xero integration status + customer→contact mapping. Access enforced by the
// family +layout.ts guard.
export async function load({ fetch }) {
  if (!hasStoredClientSession()) {
    return {
      xero: null as XeroStatus | null,
      contacts: [] as XeroContact[],
      contactsStubbed: false,
      links: [] as XeroContactLinkRow[]
    };
  }

  try {
    const [xero, contactList, links] = await Promise.all([
      api.orderingAdmin.xeroStatus(fetch),
      api.orderingAdmin.xeroContacts(fetch),
      api.orderingAdmin.xeroContactLinks(fetch)
    ]);
    return {
      xero,
      contacts: contactList.contacts,
      contactsStubbed: contactList.stubbed,
      links
    };
  } catch {
    return {
      xero: null as XeroStatus | null,
      contacts: [] as XeroContact[],
      contactsStubbed: false,
      links: [] as XeroContactLinkRow[]
    };
  }
}
