/**
 * Demo Data Seeding Script
 * Inserts comprehensive demo data into LiteMall database.
 * Run: node seed-demo.js
 */
const path = require('path');
const dbPath = path.join(__dirname, 'data', 'litemall.db');
const Database = require('better-sqlite3');

console.log('📦 Opening database:', dbPath);
const db = new Database(dbPath);
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');

const now = new Date().toISOString().replace('T', ' ').substring(0, 19);
const today = now.substring(0, 10);

// ========================
// 1. Categories (8个)
// ========================
console.log('📁 Seeding categories...');
const catData = [
  { name: '客厅灯具', pid: 0, icon: '💡', sort: 1 },
  { name: '卧室灯饰', pid: 0, icon: '🛏️', sort: 2 },
  { name: '智能照明', pid: 0, icon: '🤖', sort: 3 },
  { name: '数码配件', pid: 0, icon: '📱', sort: 4 },
  { name: '家居生活', pid: 0, icon: '🏠', sort: 5 },
  { name: '办公用品', pid: 0, icon: '📎', sort: 6 },
  { name: '厨房电器', pid: 0, icon: '🍳', sort: 7 },
  { name: '户外照明', pid: 0, icon: '🌲', sort: 8 },
];

const insertCat = db.prepare(
  'INSERT OR IGNORE INTO categories (id, name, pid, icon, image, sort, status, created_at) VALUES (?, ?, ?, ?, ?, ?, 1, ?)'
);
catData.forEach((c, i) => {
  const id = i + 1;
  const existing = db.prepare('SELECT id FROM categories WHERE id=?').get(id);
  if (!existing) {
    insertCat.run(id, c.name, c.pid, c.icon, '', c.sort, now);
  } else {
    db.prepare('UPDATE categories SET name=?, icon=?, sort=? WHERE id=?').run(c.name, c.icon, c.sort, id);
  }
});

// ========================
// 2. Products (18个经典SKU)
// ========================
console.log('📦 Seeding products...');
const prodData = [
  { name: 'LED智能灯带 5米幻彩', subtitle: '手机APP控制 | 1600万色 | 语音遥控', cat: 1, price: 69.90, orig: 128, stock: 500, img: 'https://picsum.photos/seed/p1/400/400', is_new: 1, is_hot: 1, unit: '卷' },
  { name: '北欧落地灯 客厅LED', subtitle: '无极调光 | 三色温 | 极简设计', cat: 1, price: 329, orig: 599, stock: 200, img: 'https://picsum.photos/seed/p2/400/400', is_new: 1, is_hot: 0, unit: '台' },
  { name: '复古床头台灯', subtitle: '暖光护眼 | 陶瓷底座 | 温馨卧室', cat: 2, price: 89.00, orig: 159, stock: 300, img: 'https://picsum.photos/seed/p3/400/400', is_new: 0, is_hot: 1, unit: '盏' },
  { name: '智能护眼台灯 Pro', subtitle: '国AA级照度 | 无蓝光 | 自动调光', cat: 2, price: 259, orig: 399, stock: 150, img: 'https://picsum.photos/seed/p4/400/400', is_new: 1, is_hot: 1, unit: '台' },
  { name: 'LED筒灯 嵌入式 7W', subtitle: '防眩光 | 4000K自然光 | 三年质保', cat: 1, price: 25.00, orig: 45, stock: 1000, img: 'https://picsum.photos/seed/p5/400/400', is_new: 0, is_hot: 0, unit: '个' },
  { name: '太阳能户外草坪灯', subtitle: 'IP65防水 | 自动感应 | 暖光', cat: 8, price: 39.90, orig: 79, stock: 400, img: 'https://picsum.photos/seed/p6/400/400', is_new: 0, is_hot: 1, unit: '个' },
  { name: '人体感应小夜灯', subtitle: '光控+人体双感应 | USB充电', cat: 2, price: 29.90, orig: 49, stock: 600, img: 'https://picsum.photos/seed/p7/400/400', is_new: 0, is_hot: 1, unit: '个' },
  { name: '智能门锁 指纹密码', subtitle: '半导体指纹 | 虚位密码 | APP远程', cat: 3, price: 899, orig: 1499, stock: 80, img: 'https://picsum.photos/seed/p8/400/400', is_new: 1, is_hot: 0, unit: '把' },
  { name: 'WiFi智能插座 定时版', subtitle: '远程控制 | 电量统计 | 语音控制', cat: 3, price: 49.00, orig: 89, stock: 350, img: 'https://picsum.photos/seed/p9/400/400', is_new: 0, is_hot: 1, unit: '个' },
  { name: '无线蓝牙耳机 Pro', subtitle: 'ANC主动降噪 | 30h续航 | IPX5', cat: 4, price: 299, orig: 599, stock: 200, img: 'https://picsum.photos/seed/p10/400/400', is_new: 1, is_hot: 1, unit: '副' },
  { name: '快充充电宝 20000mAh', subtitle: '65W双向快充 | 数显 | 飞机可带', cat: 4, price: 129, orig: 229, stock: 280, img: 'https://picsum.photos/seed/p11/400/400', is_new: 0, is_hot: 0, unit: '个' },
  { name: 'Type-C 数据线 1.5m', subtitle: '100W快充 | 编织线 | 锌合金头', cat: 4, price: 19.90, orig: 35, stock: 800, img: 'https://picsum.photos/seed/p12/400/400', is_new: 0, is_hot: 1, unit: '根' },
  { name: '智能扫地机器人', subtitle: 'LDS激光导航 | 4000Pa大吸力', cat: 5, price: 1499, orig: 2499, stock: 60, img: 'https://picsum.photos/seed/p13/400/400', is_new: 0, is_hot: 1, unit: '台' },
  { name: '桌面收纳盒 三格', subtitle: '竹木材质 | 分格设计 | 简约', cat: 5, price: 39.90, orig: 59, stock: 300, img: 'https://picsum.photos/seed/p14/400/400', is_new: 1, is_hot: 0, unit: '个' },
  { name: '家用空气炸锅 5L', subtitle: '无油烹饪 | 可视窗口 | 8大菜单', cat: 7, price: 269, orig: 449, stock: 120, img: 'https://picsum.photos/seed/p15/400/400', is_new: 1, is_hot: 1, unit: '台' },
  { name: '胶囊咖啡机', subtitle: '一键萃取 | 19Bar高压 | 小巧', cat: 7, price: 399, orig: 699, stock: 90, img: 'https://picsum.photos/seed/p16/400/400', is_new: 0, is_hot: 0, unit: '台' },
  { name: '无线鼠标 静音版', subtitle: '2.4G+蓝牙双模 | 人体工学 | 充电', cat: 6, price: 59.90, orig: 99, stock: 450, img: 'https://picsum.photos/seed/p17/400/400', is_new: 0, is_hot: 1, unit: '个' },
  { name: 'LED充电露营灯', subtitle: 'IPX5防水 | 360°照明 | 10h续航', cat: 8, price: 49.00, orig: 85, stock: 200, img: 'https://picsum.photos/seed/p18/400/400', is_new: 1, is_hot: 0, unit: '个' },
];

// Clear existing products that are just test data (keep categories)
const existingProds = db.prepare('SELECT id, name FROM products').all();
console.log(`  Existing products: ${existingProds.length}`);

// Delete old test products if they're clearly fake/test
const testIds = existingProds.filter(p => p.name.startsWith('测试') || p.name.startsWith('调试')).map(p => p.id);
if (testIds.length > 0) {
  console.log(`  Removing ${testIds.length} old test products...`);
  const del = db.prepare('DELETE FROM products WHERE id = ?');
  for (const id of testIds) {
    db.prepare('DELETE FROM product_skus WHERE product_id = ?').run(id);
    db.prepare('DELETE FROM product_specs WHERE product_id = ?').run(id);
    db.prepare('DELETE FROM product_images WHERE product_id = ?').run(id);
    db.prepare('DELETE FROM carts WHERE product_id = ?').run(id);
    db.prepare('DELETE FROM order_items WHERE product_id = ?').run(id);
    db.prepare('DELETE FROM user_favorites WHERE product_id = ?').run(id);
    del.run(id);
  }
}

const insertProd = db.prepare(`INSERT INTO products 
  (name, subtitle, category_id, brand, unit, image, images, description, spec_type, 
   price, original_price, cost_price, stock, sales, min_qty, max_qty, weight, 
   shipping_template_id, status, is_new, is_hot, is_recommend, sort, created_at, updated_at)
  VALUES (?, ?, ?, '', ?, ?, '', '', 0, ?, ?, ?, ?, FLOOR(RANDOM()*100), 1, 99, 0.3, 0, 1, ?, ?, 0, ?, ?, ?)`);

let prodCount = 0;
prodData.forEach((p, i) => {
  const existing = db.prepare('SELECT id FROM products WHERE name = ?').get(p.name);
  if (existing) {
    // Update existing
    db.prepare(`UPDATE products SET subtitle=?, category_id=?, unit=?, image=?, price=?, 
      original_price=?, stock=?, is_new=?, is_hot=?, sort=?, updated_at=? WHERE id=?`)
      .run(p.subtitle, p.cat, p.unit, p.img, p.price, p.orig, p.stock, p.is_new, p.is_hot, i+1, now, existing.id);
    prodCount++;
  } else {
    const r = insertProd.run(p.name, p.subtitle, p.cat, p.unit, p.img, p.price, p.orig, p.price*0.5, p.stock, p.is_new, p.is_hot, i+1, now, now);
    prodCount++;
  }
});
console.log(`  ${prodCount} products ready`);

// ========================
// 3. Banners (4个)
// ========================
console.log('🖼️ Seeding banners...');
const bannerData = [
  { title: '夏日灯饰节 · 全场满减', image: 'https://picsum.photos/seed/banner1/800/300', sort: 1 },
  { title: '新品首发 · 智能照明系列', image: 'https://picsum.photos/seed/banner2/800/300', sort: 2 },
  { title: '会员日专享 · 折上再折', image: 'https://picsum.photos/seed/banner3/800/300', sort: 3 },
  { title: '数码配件 · 限时秒杀', image: 'https://picsum.photos/seed/banner4/800/300', sort: 4 },
];

const bannerIns = db.prepare('INSERT OR REPLACE INTO banners (id, title, image, url, sort, status, created_at) VALUES (?, ?, ?, ?, ?, 1, ?)');
bannerData.forEach((b, i) => {
  const id = i + 1;
  const existing = db.prepare('SELECT id FROM banners WHERE id=?').get(id);
  if (existing) {
    db.prepare('UPDATE banners SET title=?, image=?, sort=? WHERE id=?').run(b.title, b.image, b.sort, id);
  } else {
    bannerIns.run(id, b.title, b.image, '', b.sort, now);
  }
});
console.log('  ✓ 4 banners ready');

// ========================
// 4. System Config
// ========================
console.log('⚙️ Updating system config...');
const configUpdates = [
  // Site info
  ['site_name', 'LiteMall 轻商城'],
  ['site_logo', ''],
  ['site_keywords', '灯具,照明,灯带,智能家居,电商商城'],
  ['site_description', 'LiteMall轻商城 - 专注高端照明的轻量级电商平台'],
  ['site_contact_phone', '400-888-0000'],
  ['site_contact_email', 'hello@litemall.com'],
  ['site_footer', '© 2026 LiteMall 轻商城. All rights reserved.'],
  ['site_beian', '粤ICP备2026XXXXXX号'],
  ['icp_beian', '粤ICP备2026XXXXXX号'],
  ['contact_phone', '400-888-0000'],
  ['contact_email', 'hello@litemall.com'],
  // Share
  ['share_title', 'LiteMall 轻商城 - 品质好物一站购齐'],
  ['share_desc', '精选高端照明产品，智能家居新体验。首单立减，会员专享！'],
  ['share_image', 'https://picsum.photos/seed/logo/200/200'],
  // Auth
  ['captcha_enabled', '0'],
  ['operate_mode', 'test'],
];

const updateConfig = db.prepare("UPDATE system_config SET value=? WHERE key=?");
configUpdates.forEach(([key, value]) => {
  const r = updateConfig.run(value, key);
  if (r.changes === 0) {
    db.prepare("INSERT INTO system_config (group_name, key, value, type, description) VALUES ('site', ?, ?, 'text', '')").run(key, value);
  }
});
console.log('  ✓ System config updated');

// ========================
// 5. Users (demo users)
// ========================
console.log('👤 Checking demo users...');
const bcrypt = require('bcryptjs');
const adminPwd = bcrypt.hashSync('admin888', 10);
const userPwd = bcrypt.hashSync('123456', 10);

const demoUsers = [
  { id: 1, phone: 'admin', nickname: '管理员', password: adminPwd, status: 1 },
  { id: 2, phone: '13800138001', nickname: '张三', password: userPwd, status: 1 },
  { id: 3, phone: '13800138002', nickname: '李四', password: userPwd, status: 1 },
  { id: 4, phone: '13800138003', nickname: '王五', password: userPwd, status: 1 },
  { id: 5, phone: '13800138004', nickname: '赵六', password: userPwd, status: 1 },
];

const upsertUser = db.prepare(`INSERT INTO users (id, phone, nickname, password, status, created_at, updated_at)
  VALUES (?, ?, ?, ?, ?, ?, ?)
  ON CONFLICT(id) DO UPDATE SET nickname=excluded.nickname, status=excluded.status, updated_at=excluded.updated_at`);
demoUsers.forEach(u => {
  upsertUser.run(u.id, u.phone, u.nickname, u.password, u.status, now, now);
});
console.log(`  ✓ ${demoUsers.length} demo users ready`);

// ========================
// 6. Coupons (demo coupons)
// ========================
console.log('🎫 Seeding coupons...');
const couponData = [
  { name: '新人专享券', type: 'full_reduce', value: 10, min_amount: 50, total_count: 1000, per_limit: 1, valid_days: 30 },
  { name: '满200减30', type: 'full_reduce', value: 30, min_amount: 200, total_count: 500, per_limit: 1, valid_days: 30 },
  { name: '满500减80', type: 'full_reduce', value: 80, min_amount: 500, total_count: 200, per_limit: 1, valid_days: 60 },
  { name: '全场9折券', type: 'discount', value: 10, min_amount: 0, total_count: 300, per_limit: 1, valid_days: 15 },
];
const existingCoupons = db.prepare('SELECT COUNT(*) as c FROM coupons').get().c;
if (existingCoupons < 4) {
  const insCoup = db.prepare(`INSERT INTO coupons (name, type, value, min_amount, total_count, per_limit, valid_days, status, created_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?)`);
  couponData.forEach(c => insCoup.run(c.name, c.type, c.value, c.min_amount, c.total_count, c.per_limit, c.valid_days, now));
  console.log('  ✓ 4 coupons created');
} else {
  console.log('  ✓ Coupons already exist');
}

db.close();
console.log('\n✅ Demo data seeding complete!');
console.log(`   Categories: ${catData.length}`);
console.log(`   Products: ${prodData.length}`);
console.log(`   Banners: ${bannerData.length}`);
console.log(`   Users: ${demoUsers.length}`);
console.log(`   Coupons: ${couponData.length}`);
