/**
 * GeneratePreviewService
 * Service for tracking media preview history
 */
class GeneratePreviewService {
  constructor() {
    this.baseUrl = "https://back.disploy.com/api/GeneratePreview/AddorUpdatePreviewHistory";
  }

  /**
   * Helper function to safely parse integer values from dynamic data
   */
  safeParseInt(value, defaultValue) {
    if (value === null || value === undefined) return defaultValue;
    if (typeof value === 'number') return Math.floor(value);
    if (typeof value === 'string') {
      const parsed = parseInt(value, 10);
      return isNaN(parsed) ? defaultValue : parsed;
    }
    return defaultValue;
  }

  /**
   * Add or update preview history
   * @param {Object} params - Preview history parameters
   * @returns {Promise<void>}
   */
  async addOrUpdatePreviewHistory({
    mediaTypeID,
    mediaID,
    isDefaultAsset,
    currentSystemDateTime,
    screenID,
    previewType,
    systemStartTime,
    macid,
  }) {
    // Parse IDs to integers safely
    const parsedMediaTypeID = this.safeParseInt(mediaTypeID, 0);
    const parsedMediaID = this.safeParseInt(mediaID, 0);
    const parsedScreenID = this.safeParseInt(screenID, 0);

    const body = {
      mediaTypeID: parsedMediaTypeID,
      mediaID: parsedMediaID,
      isDefaultAsset: isDefaultAsset,
      currentSystemDateTime: currentSystemDateTime.toISOString(),
      screenID: parsedScreenID,
      previewType: previewType,
      systemStartTime: systemStartTime.toISOString(),
      macid: macid,
    };

    console.log(`GeneratePreview URL: ${this.baseUrl}\nBODY: ${JSON.stringify(body)}`);

    try {
      const response = await fetch(this.baseUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        body: JSON.stringify(body),
      });

      if (response.ok) {
        const responseBody = await response.text();
        console.log(`GeneratePreview API call successful: ${responseBody}`);
      } else {
        console.log(`GeneratePreview API call failed with status: ${response.status}`);
        const responseBody = await response.text();
        console.log(`Response: ${responseBody}`);
      }
    } catch (error) {
      console.log(`Error calling GeneratePreview API: ${error}`);
      console.log(`Request parameters - mediaTypeID: ${parsedMediaTypeID}, mediaID: ${parsedMediaID}, screenID: ${parsedScreenID}, previewType: ${previewType}`);
    }
  }
}

// Export for use in other scripts
const generatePreviewService = new GeneratePreviewService();
