/**
 * Service for fetching partner branding from the GraphQL API
 */

const GRAPHQL_ENDPOINT = "https://api.xapp.ai/graphql";

const PARTNER_BRANDING_QUERY = `
  query GetPartnerBranding($code: String!) {
    public {
      partnerBranding(partnerCode: $code) {
        partnerCode
        logoUrl
        primaryColor
        backgroundColor
        companyName
        companyWebsite
      }
    }
  }
`;

export interface PartnerBranding {
    partnerCode: string;
    logoUrl: string;
    primaryColor: string;
    backgroundColor: string;
    companyName: string;
    companyWebsite: string;
}

/**
 * Cache for partner branding to reduce API calls
 */
const brandingCache = new Map<string, PartnerBranding | null>();

/**
 * Fetch partner branding from the GraphQL API
 * @param partnerCode - The partner code to fetch branding for
 * @returns Partner branding data or null if not found
 */
async function fetchPartnerBranding(partnerCode: string): Promise<PartnerBranding | null> {
    try {
        const response = await fetch(GRAPHQL_ENDPOINT, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
                query: PARTNER_BRANDING_QUERY,
                variables: { code: partnerCode },
            }),
        });

        if (!response.ok) {
            console.error(
                `Error fetching partner branding: HTTP ${response.status} ${response.statusText}`
            );
            return null;
        }

        const { data, errors } = await response.json();
        if (errors) {
            console.error("GraphQL errors fetching partner branding:", errors);
            return null;
        }

        return data?.public?.partnerBranding ?? null;
    } catch (error) {
        console.error("Failed to fetch partner branding:", error);
        return null;
    }
}

/**
 * Get partner branding with caching support
 * @param partnerCode - The partner code to fetch branding for
 * @returns Partner branding data or null if not found
 */
export async function getPartnerBranding(
    partnerCode: string
): Promise<PartnerBranding | null> {
    // Check cache first
    if (brandingCache.has(partnerCode)) {
        return brandingCache.get(partnerCode)!;
    }

    // Fetch from API
    const branding = await fetchPartnerBranding(partnerCode);

    // Cache the result (even if null to avoid repeated failed requests)
    brandingCache.set(partnerCode, branding);

    return branding;
}

/**
 * Clear the branding cache
 * Useful for testing or forcing a refresh
 */
export function clearBrandingCache(): void {
    brandingCache.clear();
}
