/**
 * Extracts GTIN and Serial Number from a given data based on provided configurations.
 * @param {string} data - The data to decode.
 * @param {Object} config - Configuration object defining parsing rules.
 * @returns {Object|string} - Extracted data object or an error message.
 */
export const decodeQR = function (data, config) {
  // Iterate through each pattern to find a match
    let extractedData = {}

    const urlObject = new URL(data)
    if (config.type === 'path-query') {
      const pathSegments = urlObject.pathname.split('/').filter(segment => segment) // Remove empty segments
      /**
       * Example Pattern Configuration:
       * {
       *   type: 'path-query',
       *   pathIndex: -1, // Last segment in the path
       *   queryParams: {
       *     SerialNumber: 'sn',
       *     GTIN: 'gtin' // Optional if GTIN is in path
       *   }
       * }
       */

      // Extract GTIN from path if specified
      if (config.pathIndex !== undefined) {
        let gtin = ''
        if (config.pathIndex >= 0) {
          gtin = pathSegments[config.pathIndex]
        } else {
          // Negative index for counting from the end
          gtin = pathSegments[pathSegments.length + config.pathIndex]
        }
        extractedData.GTIN = gtin || null
      }

      // Extract Serial Number from query parameters
      for (const [key, param] of Object.entries(config.queryParams)) {
        const value = urlObject.searchParams.get(param)
        extractedData[key] = value || null
      }

      // Check if required fields are present
      const requiredFields = Object.keys(config.queryParams)
      let allFieldsPresent = requiredFields.every(field => extractedData[field])

      // If GTIN is also required, ensure it's present
      if (config.requireGTINInPath && !extractedData.GTIN) {
        allFieldsPresent = false
      }

      if (allFieldsPresent) {
        return extractedData
      }
    } else if (config.type === 'query-delimited') {
      const queryString = urlObject.search.substring(1) // Remove the '?' at the beginning
      /**
       * Example Pattern Configuration:
       * {
       *   type: 'query-delimited',
       *   delimiter: '!',
       *   sequence: ['SerialNumber', 'GTIN']
       * }
       */

      const delimiter = config.delimiter || '!'
      const dataSegments = queryString.split(delimiter)

      if (dataSegments.length >= config.sequence.length) {
        config.sequence.forEach((field, index) => {
          extractedData[field] = dataSegments[index] || null
        })

        // Check if all required fields are present
        const allFieldsPresent = config.sequence.every(field => extractedData[field])
        if (allFieldsPresent) {
          return extractedData
        }
      }
    }

  return 'No matching config found or required data is missing.'
}

// // Example configuration for both URL formats
// const config = {
//   patterns: [
//     {
//       type: 'path-query',
//       pathIndex: -1, // Last segment in the path
//       requireGTINInPath: true,
//       queryParams: {
//         SerialNumber: 'sn'
//         // GTIN can also be included here if it appears in query params
//       }
//     },
//     {
//       type: 'query-delimited',
//       delimiter: '!',
//       sequence: ['SerialNumber', 'GTIN']
//     }
//   ]
// }

// // Example Usage:
// // Case 1: URL with GTIN in path and Serial Number in query param
// const url1 = 'https://example.com/product/01234567890512?sn=ABC123456789'
// const result1 = extractDataFromURL(url1, config)
// console.log('Result for URL 1:', result1)
// // Expected Output:
// // Result for URL 1: { GTIN: '01234567890512', SerialNumber: 'ABC123456789' }

// // Case 2: URL with Serial Number and GTIN in query string separated by '!'
// const url2 = 'https://kr.riman.com/?IDC00000718!8800267650480'
// const result2 = extractDataFromURL(url2, config)
// console.log('Result for URL 2:', result2)
// // Expected Output:
// // Result for URL 2: { SerialNumber: 'IDC00000718', GTIN: '8800267650480' }
