const fs = require('fs')
const path = require('path')
const XLSX = require('xlsx')
const { parse } = require('csv-parse/sync')
const { pool } = require('../database')

async function createMatieresBatch(records) {
  try {
    // Step 1: Get uniter_heure once
    const uniterHeureSql = 'SELECT uniter_heure FROM nessesaryTable LIMIT 1'
    const [rows] = await pool.query(uniterHeureSql)
    const uniterHeureValue = rows[0]?.uniter_heure ?? 1 // fallback 1 if not found

    // Step 2: Prepare bulk insert values
    // Each row: [nom, uniter, credit, heure, ue]
    const values = records.map(({ nom, credit, uniter, ue }) => {
      const heure = credit * uniterHeureValue
      return [nom, uniter, credit, heure, ue]
    })

    // Step 3: Bulk insert query
    const insertSql = `
      INSERT INTO matieres (nom, unite_enseignement, credit, heure, ue)
      VALUES ?
    `

    const [result] = await pool.query(insertSql, [values])

    return {
      success: true,
      insertedCount: result.affectedRows,
      insertId: result.insertId
    }
  } catch (error) {
    return { success: false, error: 'Erreur veuillez réessayer: ' + error.message }
  }
}

/**
 * Function to import data from the first column of an XLSX or CSV file into SQLite database
 * @param {string} filePath - Path to the file (either .xlsx or .csv)
 */
async function importFileToDatabaseMatiere(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 {
    let message = ''
    let error = true
    for (const row of records) {
      if (!row.nom || !row.credit || !row.uniter || !row.ue) {
        if (!row.nom) {
          message = "Le champ 'nom' est inconnu"
        } else if (!row.credit) {
          message = "Le champ 'credit' est inconnu"
        } else if (!row.uniter) {
          message = "Le champ 'uniter' est inconnu"
        } else if (!row.ue) {
          message = "Le champ 'UE' est inconnu"
        }
        error = false
        break
      }
    }

    if (error !== false) {
      createMatieresBatch(records)
    }

    return { error, message }
  } catch (error) {
    console.error('Error inserting record:', error)
  }
}

module.exports = {
  importFileToDatabaseMatiere
}
