import axios from 'axios'; import type { ISeoAnalyticsApiRow, ISeoAnalyticsList, ISeoAnalyticsListQuery, ISeoAnalyticsOverview, ISeoAnalyticsPeriod, ISeoGoogleProperties, ISeoGoogleStatus, } from './seo-analytics.interface'; // axios carries the dashboard-api base URL (…/api) and the merchant's JWT // from service/config.ts, so these are plain paths under it. The API // answers with its envelope, the data spread next to message and success. const GOOGLE = '/v2/connectors/google'; const ANALYTICS = '/v2/seo/analytics'; const message = (reason: unknown): string => { if (axios.isAxiosError(reason)) { const body = reason.response?.data as | { message?: string; error?: string } | undefined; return ( body?.message ?? body?.error ?? reason.message ?? 'The Recomaze API did not answer.' ); } return (reason as Error).message; }; const call = async (request: Promise<{ data: T }>): Promise => { try { return (await request).data; } catch (reason) { throw new Error(message(reason)); } }; export const fetchGoogleStatus = (): Promise => call(axios.get(`${GOOGLE}/status`)); export const fetchGoogleConnectUrl = ( returnUrl: string ): Promise<{ url: string }> => call(axios.get(`${GOOGLE}/connect`, { params: { return: returnUrl } })); export const fetchGoogleProperties = (): Promise => call(axios.get(`${GOOGLE}/properties`)); export const chooseGoogleProperties = (choice: { site_url?: string; ga4_property?: string; }): Promise<{ site_url: string | null; syncing: boolean }> => call(axios.put(GOOGLE, choice)); export const disconnectGoogle = (): Promise => call(axios.delete(GOOGLE)); export const requestAnalyticsSync = (): Promise<{ queued: boolean }> => call(axios.post(`${ANALYTICS}/sync`)); export const fetchAnalyticsOverview = ( period: ISeoAnalyticsPeriod ): Promise => call(axios.get(`${ANALYTICS}/overview`, { params: period })); const flatten = ( list: Omit & { rows: ISeoAnalyticsApiRow[] } ): ISeoAnalyticsList => ({ ...list, rows: list.rows.map(row => ({ key: row.query ?? row.page ?? '', ...row.current, previous: row.previous, })), }); export const fetchAnalyticsKeywords = async ( query: ISeoAnalyticsListQuery ): Promise => flatten(await call(axios.get(`${ANALYTICS}/keywords`, { params: query }))); export const fetchAnalyticsPages = async ( query: ISeoAnalyticsListQuery ): Promise => flatten(await call(axios.get(`${ANALYTICS}/pages`, { params: query })));