import { createQuery } from '@tanstack/svelte-query';
import { api } from './client';

// Mirrors internal/api/me_recommendation_metrics.go.
export type RecommendationMetric = {
  source: string;
  plays: number;
  skips: number;
  skip_rate: number;
  avg_completion: number;
};

export type RecommendationMetrics = {
  window_days: number;
  sources: RecommendationMetric[];
};

export function getRecommendationMetrics(): Promise<RecommendationMetrics> {
  return api.get<RecommendationMetrics>('/api/me/recommendation-metrics');
}

export const REC_METRICS_QUERY_KEY = ['settings', 'recommendation-metrics'] as const;

export function createRecommendationMetricsQuery() {
  return createQuery({
    queryKey: REC_METRICS_QUERY_KEY,
    queryFn: getRecommendationMetrics,
    staleTime: 60_000
  });
}

// Friendly labels for the system-playlist source keys (play_events.source).
const SOURCE_LABELS: Record<string, string> = {
  for_you: 'For You',
  discover: 'Discover',
  deep_cuts: 'Deep cuts',
  rediscover: 'Rediscover',
  new_for_you: 'New for you',
  on_this_day: 'On this day',
  first_listens: 'First listens',
  songs_like_artist: 'Songs like…'
};

export function sourceLabel(source: string): string {
  return SOURCE_LABELS[source] ?? source;
}
