import { getRuntimeCompanyId, getRuntimeExtensionId } from './runtimeContext'; import { getChannelId, isChannelActive, normalizeChannelsPayload, } from './businessProfile'; const FYND_PORTAL_API_BASE = 'https://api.fynd.com'; function normalizeText(value) { return typeof value === 'string' ? value.trim() : ''; } function normalizeWebsiteUrl(value) { const rawValue = normalizeText(value); if (!rawValue) return ''; const candidate = /^https?:\/\//i.test(rawValue) ? rawValue : `https://${rawValue}`; try { return new URL(candidate).toString().replace(/\/$/, ''); } catch { return ''; } } function readCookie(name) { if (typeof document === 'undefined') return ''; const cookies = `; ${document.cookie || ''}`; const parts = cookies.split(`; ${name}=`); if (parts.length < 2) return ''; return parts.pop().split(';').shift() || ''; } function buildPortalRequestUrl(companyId, extensionId) { const search = new URLSearchParams({ company_id: companyId, page_no: '1', page_size: '100', query: JSON.stringify({ is_active: true }), }); if (extensionId) { search.set('extension_id', extensionId); } return `${FYND_PORTAL_API_BASE}/service/portal/configuration/v1.0/company/${encodeURIComponent(companyId)}/application?${search.toString()}`; } function buildPortalHeaders() { const headers = { accept: 'application/json, text/plain, */*', }; const token = normalizeText(readCookie('token')); if (token) { headers.authorization = `Bearer ${token}`; } return headers; } function withDerivedWebsiteUrl(channel) { const explicitWebsiteUrl = normalizeWebsiteUrl( channel?.websiteUrl || channel?.domain || channel?.url ); return explicitWebsiteUrl ? { ...channel, websiteUrl: explicitWebsiteUrl } : channel; } export async function fetchActiveSalesChannels() { const companyId = getRuntimeCompanyId(); const extensionId = getRuntimeExtensionId(); if (!companyId) { throw new Error('Company ID is unavailable for fetching sales channels.'); } const response = await fetch(buildPortalRequestUrl(companyId, extensionId), { method: 'GET', credentials: 'include', headers: buildPortalHeaders(), }); const payload = await response.json().catch(() => null); if (!response.ok) { const message = normalizeText(payload?.message || payload?.error) || `Sales channels could not be fetched (${response.status}).`; throw new Error(message); } return normalizeChannelsPayload(payload) .map(withDerivedWebsiteUrl) .filter((channel) => isChannelActive(channel) && getChannelId(channel)); }