import { ApiClient } from '@/lib/apiClient';

export const SHAREABLE_CONTENT_TYPES = ['song', 'hook'] as const;
export const SHAREABLE_CONTENT_TYPE_PATH_PREFIXES = SHAREABLE_CONTENT_TYPES.map(
  (type) => `/${type}/`
);
export type ShareContentType = (typeof SHAREABLE_CONTENT_TYPES)[number];

// Create a module-level cache
const shareLinkCache: Record<string, string> = {};

export function getContentTypeFromPath(path: string) {
  const contentType = SHAREABLE_CONTENT_TYPE_PATH_PREFIXES.find((prefix) =>
    path.startsWith(prefix)
  )?.replaceAll('/', '') as ShareContentType;
  return contentType || null;
}

// Helper to generate a consistent cache key
function generateShareLinkCacheKey(
  contentType: ShareContentType,
  contentId: string,
  platform?: string,
  ...restParams: (string | undefined)[]
): string {
  return [contentType, contentId, platform || 'none', ...restParams].join('-');
}

export async function getShareLink(options: {
  apiClient: ApiClient;
  contentType: ShareContentType;
  contentId: string;
  platform?: string;
  recommendationItemId?: string;
}): Promise<string> {
  const { apiClient, contentType, contentId, platform, recommendationItemId } =
    options;
  const cacheKey = generateShareLinkCacheKey(
    contentType,
    contentId,
    platform,
    recommendationItemId
  );

  // Check if we have a cached result
  if (shareLinkCache[cacheKey] && shareLinkCache[cacheKey] !== '') {
    return shareLinkCache[cacheKey];
  }

  const shareLinkResponse = await apiClient.POST('/api/share/link', {
    body: {
      content_type: contentType,
      content_id: contentId,
      source: 'web',
      platform: platform,
      ...(recommendationItemId && {
        recommendation_metadata: {
          recommendation_item_id: recommendationItemId,
        },
      }),
    },
  });

  // Get the result
  const link = shareLinkResponse.data?.link || '';

  // Cache the result
  shareLinkCache[cacheKey] = link;

  return link;
}

export async function getShareCodeDetails(
  apiClient: ApiClient,
  shareCode: string
) {
  const { data } = await apiClient.GET('/api/share/code/{share_id}', {
    params: {
      path: { share_id: shareCode },
    },
  });

  return data;
}
