require('dotenv').config({ path: require('path').join(__dirname, '..', '.env') })

const fs = require('fs')
const path = require('path')
const mysql = require('mysql2/promise')
const config = require('../src/config')
const { hashPassword, randomHex } = require('../src/lib/auth')

async function main() {
  const conn = await mysql.createConnection({
    host: config.db.host,
    port: config.db.port,
    user: config.db.user,
    password: config.db.password,
    database: config.db.database,
    multipleStatements: true
  })

  const schema = fs.readFileSync(path.join(__dirname, '..', 'sql', 'schema.sql'), 'utf8')
  await conn.query(schema)

  await conn.query("ALTER TABLE devices MODIFY product_id VARCHAR(64) NOT NULL DEFAULT 'HOX_LIGHT_MASK'").catch(() => {})
  await conn.query("ALTER TABLE admin_accounts MODIFY password_hash VARCHAR(100) NOT NULL").catch(() => {})
  await conn.query("ALTER TABLE admin_accounts MODIFY password_salt VARCHAR(32) NOT NULL DEFAULT ''").catch(() => {})

  const [rows] = await conn.execute('SELECT admin_id FROM admin_accounts WHERE username = ?', [config.admin.username])
  if (rows.length === 0) {
    const passwordHash = hashPassword(config.admin.password)
    await conn.execute(
      'INSERT INTO admin_accounts (username, password_hash, password_salt, real_name, role, status) VALUES (?, ?, ?, ?, ?, 1)',
      [config.admin.username, passwordHash, '', '管理员', 'admin']
    )
  }

  await conn.end()
  console.log('Database initialized:', config.db.database)
}

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