const fs = require('fs')
const path = require('path')
const XLSX = require('xlsx')
const { parse } = require('csv-parse/sync')
const { insertNiveau } = require('../Models/Niveau')

async function importNiveau(filePath) {
  const fileExtension = path.extname(filePath).toLowerCase()

  // Determine the file type and parse accordingly
  let records
  if (fileExtension === '.xlsx') {
    // Read and parse XLSX file
    const workbook = XLSX.readFile(filePath)
    const worksheet = workbook.Sheets[workbook.SheetNames[0]] // Assuming data is in the first sheet
    records = XLSX.utils.sheet_to_json(worksheet, { defval: '' })
  } else if (fileExtension === '.csv') {
    // Read and parse CSV file
    const fileContent = fs.readFileSync(filePath, 'utf8')
    records = parse(fileContent, {
      columns: true,
      skip_empty_lines: true
    })
  } else {
    console.error('Unsupported file format. Only .xlsx and .csv are allowed.')
    return
  }

  try {
    // Get the first column key dynamically
    const firstColumnKey = Object.keys(records[0])[0]
    console.log(`Detected first column key: ${firstColumnKey}`)

    for (const row of records) {
      const firstColumnValue = row[firstColumnKey] || 'null pour le moment'

      // Insert into the database
      await insertNiveau(firstColumnValue)
      console.log(`Inserted value from first column: '${firstColumnValue}'`)
    }
    console.log(
      `First column values successfully imported from ${fileExtension.toUpperCase()} file`
    )
    return { success: 'success' }
  } catch (error) {
    console.error('Error inserting record:', error)
  }
}

module.exports = {
  importNiveau
}
