import { request } from '../httpClient.ts';
import { newsItemSchema, newsPageSchema, type NewsItem, type NewsPageResponse } from './types.ts';

export interface ListNewsParams {
  page?: number;
  limit?: number;
  search?: string;
  tags?: string[];
}

const NEWS_ENDPOINT = '/api/v1/news';

const buildQuery = (params?: ListNewsParams) => {
  if (!params) {
    return undefined;
  }

  const { page, limit, search, tags } = params;
  return {
    page,
    limit,
    search,
    tags,
  };
};

export const newsApi = {
  async list(params?: ListNewsParams): Promise<NewsPageResponse> {
    return request(NEWS_ENDPOINT, newsPageSchema, {
      query: buildQuery(params),
    });
  },
  async get(slug: string): Promise<NewsItem> {
    return request(`${NEWS_ENDPOINT}/${slug}`, newsItemSchema);
  },
};
