import apiService from '../APIRequestService/APIService';

// Utility function for payload transformation (if required)
const transformPayload = (payload) => {
    return JSON.parse(JSON.stringify(payload, (key, value) => {
      if (key === "createdAt" || key === "updatedAt") {
        // Convert date strings to ISO format if they are valid dates
        if (Date.parse(value)) {
          return new Date(value).toISOString(); // Convert to ISO format
        }
        return undefined; // Ignore invalid date values
      }
      if (key === "id") {
        // Convert the id to a number if it is a valid number string
        const numId = parseInt(value, 10);
        if (!isNaN(numId)) {
          return numId; // Convert to number
        }
        return undefined; // Ignore invalid number strings
      }
      if (key === "tableName") return undefined; // Remove tableName
      if (key === "table_name") return payload.tableName; // Replace table_name with tableName
      return value;
    }));
  };
  
  
  

export const fetchRegistry = async () => {
    try {
      console.log("Fetching registry..."); // Debugging log
      const response = await apiService.get('/Api_registery_header/Api_registery_header');
      console.log("API Response:", response.data); // Verify response
      return response.data; // Ensure you're returning data
    } catch (error) {
      console.error("Error in fetchRegistry:", error); 
    }
}

export const addRegistry = async (payload) => {
    try {
      
        const transformedPayload = transformPayload(payload);
        console.log("Adding registry entry with payload:", transformedPayload);
       const response = await apiService.post('/Api_registery_header/Api_registery_header', transformedPayload);
   
       console.log(response.data);
       return response;
    } catch (error) {
        console.error("Error in addRegistry:", error);
    } }

    export const updateRegistry = async (id, payload) => {
        try {
            const transformedPayload = transformPayload(payload);
        console.log("Adding registry entry with payload:", transformedPayload);
          const response = await apiService.put(`/Api_registery_header/Api_registery_header/${id}`, transformedPayload);
          console.log(response.data);
          return response;
        } catch (error) {
          console.error("Error in updateRegistry:", error);
        }
      };

      export const deleteRegistry = async (id) => {
        try {
          const response = await apiService.delete(`/Api_registery_header/Api_registery_header/${id}`);
          console.log(response.data);
          return response;
        } catch (error) {
          console.error("Error in deleteRegistry:", error);
        }
    }