import 'dotenv/config'
import { readFileSync } from 'node:fs'
import { resolve, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
import { wingPool } from './wingDb.js'

const __dirname = dirname(fileURLToPath(import.meta.url))

// 통합 물질 데이터 JSON (기존 20종 상세 + Excel 1,202종 기본)
const dataPath = resolve(__dirname, '../../../frontend/src/data/hnsSubstanceData.json')
const HNS_SEARCH_DB = JSON.parse(readFileSync(dataPath, 'utf-8'))

async function seedHnsSubstances() {
  console.log('HNS 물질정보 시드 시작...')
  console.log(`총 ${HNS_SEARCH_DB.length}종 물질 데이터 삽입 예정`)

  const client = await wingPool.connect()

  try {
    await client.query('BEGIN')

    // 기존 데이터 삭제
    await client.query('DELETE FROM HNS_SUBSTANCE')

    let inserted = 0

    for (const s of HNS_SEARCH_DB) {
      // 검색용 컬럼 추출, 나머지는 DATA JSONB로 저장
      const { abbreviation, nameKr, nameEn, unNumber, casNumber, sebc, ...detailData } = s

      await client.query(
        `INSERT INTO HNS_SUBSTANCE (SBST_SN, ABBREVIATION, NM_KR, NM_EN, UN_NO, CAS_NO, SEBC, DATA)
         VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
         ON CONFLICT (SBST_SN) DO UPDATE SET
           ABBREVIATION = EXCLUDED.ABBREVIATION,
           NM_KR = EXCLUDED.NM_KR,
           NM_EN = EXCLUDED.NM_EN,
           UN_NO = EXCLUDED.UN_NO,
           CAS_NO = EXCLUDED.CAS_NO,
           SEBC = EXCLUDED.SEBC,
           DATA = EXCLUDED.DATA`,
        [s.id, abbreviation, nameKr, nameEn, unNumber, casNumber, sebc, JSON.stringify(detailData)]
      )

      inserted++
      if (inserted % 100 === 0) {
        console.log(`  ${inserted}/${HNS_SEARCH_DB.length}건 삽입 완료...`)
      }
    }

    await client.query('COMMIT')

    // 결과 확인
    const { rows } = await client.query('SELECT COUNT(*) as count FROM HNS_SUBSTANCE')
    console.log(`시드 완료! 총 ${rows[0].count}종의 HNS 물질이 저장되었습니다.`)
  } catch (err) {
    await client.query('ROLLBACK')
    console.error('HNS 시드 실패:', err)
    throw err
  } finally {
    client.release()
    await wingPool.end()
  }
}

seedHnsSubstances().catch((err) => {
  console.error(err)
  process.exit(1)
})
