const fs = require('fs')
const path = require('path')
const { initDatabase, query } = require('../config/database')

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

async function run() {
  try {
    console.log('Initializing database...')
    await initDatabase()
    
    console.log('Inserting categories...')
    for (const cat of categoriesData) {
      await 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 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 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)
  }
}

run()