import chronicleInstance from "@/shared/services/chronicleInstance";
import { ThemeParams } from "../hooks/useTheme";
import { CreateThemePayload, ThemeItem, ThemeResponse } from "../types/themeTypes";
import { XSSUploadValidator } from "@/shared/services/validation";
import { presignedAxios } from "@/shared/services/presignedAxios";

export const ThemeService = {
  async createItem(data: CreateThemePayload): Promise<ThemeItem[]> {
    const response = await chronicleInstance.post("/theme/bulk", data,{ headers: { "x-tenant-id": "adf98293-41ba-4bda-bdb4-70e30a70c1b7" }});
    return response.data;
  },

  async getItems(
    params: ThemeParams
  ): Promise<ThemeResponse> {
    const response = await chronicleInstance.get(`/theme/list-with-presigned`, {
      params,
      headers: { "x-tenant-id": "adf98293-41ba-4bda-bdb4-70e30a70c1b7" },
    
    });
    return response.data;
  },

  async getItem(id: string): Promise<ThemeItem> {
    const response = await chronicleInstance.get(
      `/theme/list-with-presigned/${id}`
    );
    return response.data;
  },


  async deleteItem(id: string): Promise<void> {
    await chronicleInstance.delete(`/theme/${id}`);
  },
  async updateUploadStatus(
    resourceId: string,
    id: string
  ): Promise<ThemeItem> {
    const response = await chronicleInstance.patch(`/theme/${id}/upload-status`, {
      id: id,
      parentId: resourceId,
      uploadedSuccessfully: true,
    });
    return response.data;
  },
  async changeStatus(id: string): Promise<ThemeItem> {
    const response = await chronicleInstance.put(`/theme/change-status/${id}`, {
      isCurrent: true,
    });
    return response.data;
  },

  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,
      },
    });
  }

};
