const fs = require('fs')
const path = require('path')
const mysql = require('mysql2/promise')

const categoriesData = require('../data/categories.json')
const goodsData = require('../data/goods.json')
const usersData = require('../data/users.json')

const config = {
  host: '110.42.255.239',
  port: 3306,
  user: 'root',
  password: 'Wentian9588.',
  database: 'miniprogram'
}

async function run() {
  let connection = null
  try {
    console.log('Connecting to MySQL...')
    connection = await mysql.createConnection({
      host: config.host,
      port: config.port,
      user: config.user,
      password: config.password
    })

    console.log('Creating database...')
    await connection.query(`CREATE DATABASE IF NOT EXISTS ${config.database} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`)
    await connection.query(`USE ${config.database}`)

    console.log('Granting permissions...')
    await connection.query('GRANT ALL PRIVILEGES ON miniprogram.* TO admin@"%";')
    await connection.query('FLUSH PRIVILEGES;')

    console.log('Creating tables...')
    const schema = fs.readFileSync(path.join(__dirname, '../config/schema.sql'), 'utf8')
    const statements = schema.split(';').filter(s => s.trim())
    
    for (const statement of statements) {
      await connection.query(statement)
    }

    console.log('Inserting categories...')
    for (const cat of categoriesData) {
      await connection.query(
        'INSERT INTO categories (id, name, icon, is_show, sort_order) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE name=VALUES(name), icon=VALUES(icon), is_show=VALUES(is_show), sort_order=VALUES(sort_order)',
        [cat.id, cat.name, cat.icon, cat.is_show, cat.sort_order]
      )
    }

    console.log('Inserting goods...')
    for (const good of goodsData) {
      await connection.query(
        'INSERT INTO goods (id, name, price, original_price, unit, category_id, images, stock, sales, is_hot, is_new, pricing_type, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE name=VALUES(name), price=VALUES(price), original_price=VALUES(original_price)',
        [good.id, good.name, good.price, good.original_price, good.unit, good.category_id, good.images, good.stock, good.sales, good.is_hot, good.is_new, good.pricing_type, good.description]
      )
    }

    console.log('Inserting users...')
    for (const user of usersData) {
      await connection.query(
        'INSERT INTO users (id, phone, password, name, avatar, points) VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE name=VALUES(name), points=VALUES(points)',
        [user.id, user.phone, user.password, user.name, user.avatar, user.points]
      )
    }

    console.log('Database initialization completed successfully!')
    process.exit(0)
  } catch (error) {
    console.error('Database initialization failed:', error)
    process.exit(1)
  } finally {
    if (connection) {
      await connection.end()
    }
  }
}

run()