import { CreationListItem } from '@/types/Creation';

import { javaPost } from './apiClient';

interface CreationListRequestBody {
  firstResult: number;
  maxResults: number;
  personIdList: number[] | null;
  personIdentifierList: string[] | null;
  queryString: string | null;
  contentType: string[] | null;
  imageNeeded: boolean;
  conceptionIdList: number[];
  videoType: string[] | null;
  featuredContent: boolean;
  withCoord: boolean | null;
}

const defaultBody = {
  firstResult: 0,
  maxResults: 100000,
  personIdList: null,
  personIdentifierList: null,
  queryString: null,
  contentType: null,
  imageNeeded: false,
  conceptionIdList: [],
  videoType: null,
  featuredContent: false,
  withCoord: null,
};

export async function getCreationList(
  body: Partial<CreationListRequestBody> = {},
  options = {}
): Promise<CreationListItem[]> {
  try {
    const response: unknown = await javaPost(
      'contentControl/getList',
      {
        ...defaultBody,
        ...body,
      },
      options
    );

    const rawList = Array.isArray(response)
      ? response
      : response &&
          typeof response === 'object' &&
          'list' in response &&
          Array.isArray((response as { list?: unknown }).list)
        ? (response as { list: CreationListItem[] }).list
        : [];

    return rawList.map((item: CreationListItem) => ({
      ...item,
      cardType: item.cardType || 'creation',
    }));
  } catch (error) {
    console.error('Failed to get creation list:', error);
    // Return empty response structure as fallback
    return [];
  }
}

export async function getCreationById(id: string) {
  try {
    return await javaPost('contentControl/getDataNew', {
      contentId: null,
      contentIdentifier: id,
    });
  } catch (error) {
    console.error('Failed to get creation by id:', error);
    throw error; // Re-throw for this function since it's used for individual creation pages
  }
}

export async function getFeaturedCreations(personIdentifier: string, count: number) {
  try {
    const response = await javaPost('contentControl/getFilteredList', {
      personIdentifier,
      cnt: count,
    });

    return response;
  } catch (error) {
    console.error('Failed to get featured creations:', error);
    // Return empty array as fallback instead of throwing
    return [];
  }
}
