import chronicleInstance from "@/shared/services/chronicleInstance";
import { NewsParams } from "../hooks/useNews";
import { CreateNewsPayload, NewsItem, NewsResponse } from "../types/newsTypes";
import { XSSUploadValidator } from "@/shared/services/validation";
import { presignedAxios } from "@/shared/services/presignedAxios";

// Helper function to normalize API response data
const normalizeNewsItem = (item: any): NewsItem => {
  return {
    ...item,
    // Ensure consistent property names (handle both cases)
    title: item.title || { am: "", en: "" },
    subTitle: item.subTitle || { am: "", en: "" },
    body: item.body || { am: "", en: "" },
  };
};

export const NewsService = {
  async createItem(data: CreateNewsPayload): Promise<NewsItem> {
    const response = await chronicleInstance.post("/news", data, {
      headers: { "x-tenant-id": "adf98293-41ba-4bda-bdb4-70e30a70c1b7" },
    });
    return normalizeNewsItem(response.data);
  },

  async getItems(params: NewsParams): Promise<NewsResponse> {
    const response = await chronicleInstance.get(`/news/list-with-presigned`, {
      params,
      headers: { "x-tenant-id": "adf98293-41ba-4bda-bdb4-70e30a70c1b7" },
    });
    return {
      ...response.data,
      items: response.data.items?.map(normalizeNewsItem) || [],
    };
  },

  async getItem(id: string): Promise<NewsItem> {
    // Use the list endpoint to get single item with presigned URL
    const response = await chronicleInstance.get(`/news/list-with-presigned`, {
      params: { id },
      headers: { "x-tenant-id": "adf98293-41ba-4bda-bdb4-70e30a70c1b7" },
    });
    // Return the first item from the list, normalized
    const item = response.data.items?.[0] || response.data;
    return normalizeNewsItem(item);
  },

  async updateItem(
    id: string,
    data: Partial<CreateNewsPayload>
  ): Promise<NewsItem> {
    const payload = {
      ...data,
    };
    const response = await chronicleInstance.put(`/news/${id}`, payload, {
      headers: { "x-tenant-id": "adf98293-41ba-4bda-bdb4-70e30a70c1b7" },
    });
    return normalizeNewsItem(response.data);
  },

  async deleteItem(id: string): Promise<void> {
    await chronicleInstance.delete(`/news/${id}`, {
      headers: { "x-tenant-id": "adf98293-41ba-4bda-bdb4-70e30a70c1b7" },
    });
  },

  async uploadImage(file: File, uploadUrl: string) {
    if (!uploadUrl) throw new Error("Upload URL is undefined.");

    // Validate file for XSS threats
    const validationResult = await XSSUploadValidator.validateFileForUpload(file, {
      allowedMimeTypes: ['image/png', 'image/jpeg', 'image/gif', 'image/webp'],
      allowedExtensions: ['.png', '.jpg', '.jpeg', '.gif', '.webp'],
      maxSizeMB: 10,
      uploadContext: 'signature',
    });

    if (!validationResult.isValid) {
      throw new Error(
        validationResult.clientValidation.fileName?.error ||
        validationResult.clientValidation.extension?.error ||
        validationResult.clientValidation.mimeType?.error ||
        validationResult.clientValidation.size?.error ||
        'File validation failed'
      );
    }

    return presignedAxios.put(uploadUrl, file, {
      headers: {
        "Content-Type": file.type,
      },
    });
  },

  async updateUploadStatus(
    id: string,
    uploadedSuccessfully: boolean
  ): Promise<void> {
    await chronicleInstance.patch(
      `/news/${id}/upload-status`,
      { uploadedSuccessfully },
      {
        headers: { "x-tenant-id": "adf98293-41ba-4bda-bdb4-70e30a70c1b7" },
      }
    );
  },
};
