import { apiClient } from "./client";
import type {
  CategoryListResponse,
  NewsroomCategory,
  NewsroomItem,
  NewsroomListResponse,
  NewsroomPagination,
} from "@/types/newsroom";

const DEFAULT_LIMIT = 12;

export interface FetchNewsroomsParams {
  page?: number;
  limit?: number;
  category?: string;
  year?: string | number;
}

/**
 * Fetch all categories for the newsroom filter using axios.
 */
export async function getCategories(): Promise<NewsroomCategory[]> {
  try {
    const res = await apiClient.get<CategoryListResponse>("/cat/ft");
    return Array.isArray(res.data?.result) ? res.data.result : [];
  } catch (error) {
    console.error("Error fetching newsroom categories:", error);
    return [];
  }
}

/**
 * Fetch newsroom article listing with pagination and optional category filter using axios.
 * Query Params:
 * - pg: page number
 * - lt: limit per page (default 12)
 * - ct: category id (empty string or omitted for all)
 * - yr: year filter (e.g. 2026, 2025)
 */
export async function getNewsroomList({
  page = 1,
  limit = DEFAULT_LIMIT,
  category = "",
  year = "", 
}: FetchNewsroomsParams = {}): Promise<{
  pagination: NewsroomPagination;
  latestRecord: NewsroomItem | null;
  latestRecords: NewsroomItem[];
  archiveYears: (number | string)[];
}> {
  try {
    const params: Record<string, string> = {
      pg: String(page),
      lt: String(limit),
    };

    if (category && category.trim() !== "" && category.toLowerCase() !== "all") {
      params.ct = category.trim();
    }

    if (year && String(year).trim() !== "") {
      params.yr = String(year).trim();
    }

    const res = await apiClient.get<NewsroomListResponse>("/nr/ft", { params });
    const data = res.data;


    const pagination: NewsroomPagination = data?.result || {
      docs: [],
      totalDocs: 0,
      limit,
      page,
      totalPages: 1,
      hasPrevPage: false,
      hasNextPage: false,
      prevPage: null,
      nextPage: null,
    };

    let latestRecords: NewsroomItem[] = [];
    if (Array.isArray(data?.latest_record)) {
      latestRecords = data.latest_record;
    } else if (data?.latest_record && typeof data.latest_record === "object") {
      latestRecords = [data.latest_record];
    } else if (pagination.docs.length > 0) {
      latestRecords = pagination.docs.slice(0, 3);
    }

    const archiveYears: (number | string)[] = Array.isArray(data?.ay) ? data.ay : [];

    return {
      pagination,
      latestRecord: latestRecords[0] || null,
      latestRecords,
      archiveYears,
    };
  } catch (error) {
    console.error("Error fetching newsroom list:", error);
    return {
      pagination: {
        docs: [],
        totalDocs: 0,
        limit,
        page,
        totalPages: 1,
        hasPrevPage: false,
        hasNextPage: false,
        prevPage: null,
        nextPage: null,
      },
      latestRecord: null,
      latestRecords: [],
      archiveYears: [],
    };
  }
}

/**
 * Fetch a single newsroom article by its slug or ID using axios.
 * Endpoint: /nr/ft/:slug
 */
export async function getNewsroomDetail(slug: string): Promise<NewsroomItem | null> {
  if (!slug || typeof slug !== "string" || !slug.trim()) {
    return null;
  }

  try {
    const res = await apiClient.get<{
      result?: NewsroomItem;
      related_news?: NewsroomItem[];
    }>(`/nr/ft/${encodeURIComponent(slug.trim())}`);
    const data = res.data;
    const article = data?.result || null;
    if (article) {
      if (!article.related_news && Array.isArray(data?.related_news)) {
        article.related_news = data.related_news;
      }
    }
    return article;
  } catch (error) {
    console.error(`Error fetching newsroom detail for ${slug}:`, error);
    return null;
  }
}
