'use strict';
const fs = require('fs');
const path = require('path');
const bcrypt = require('bcryptjs');
const { db, setSetting, uniqueSlug, categoriesList } = require('./db');

const IMG_DIR = path.join(__dirname, 'public', 'images', 'products');

const defaultSettings = {
  store_name: 'TOUS CINO',
  slogan: "EVERYONE'S SENSE OF FREENESS",
  tagline: 'Modern accessories, gadgets, cosmetics & drip from different brands.',
  address: '296 Justice Mahommed Street, Sunnyside, Pretoria, 0002, South Africa',
  phone: '+27 67 770 0019',
  whatsapp: '27677700019',
  email: 'wasup1606@gmail.com',
  facebook: 'https://www.facebook.com/TOUS_CINO',
  instagram: 'https://www.instagram.com/TOUS_CINO',
  business_hours: 'Open 24 Hours',
  currency: 'ZAR',
  shipping_fee: '79',
  free_shipping_threshold: '500',
  payfast_merchant_id: '',
  payfast_merchant_key: '',
  payfast_passphrase: '',
  payfast_sandbox: '1',
  smtp_host: '',
  smtp_port: '587',
  smtp_user: '',
  smtp_pass: '',
  smtp_secure: '0',
  smtp_from: 'wasup1606@gmail.com',
  maps_url:
    'https://www.google.com/maps/dir/?api=1&destination=296+Justice+Mahommed+Street,+Sunnyside,+Pretoria,+0002,+South+Africa',
};

function run() {
  for (const [k, v] of Object.entries(defaultSettings)) {
    if (db.prepare('SELECT 1 FROM settings WHERE key = ?').get(k) === undefined) {
      setSetting(k, v);
    }
  }

  const catCount = db.prepare('SELECT COUNT(*) AS c FROM categories').get().c;
  if (catCount === 0) {
    const cats = [
      ['gadgets', 'Gadgets', 'Smart tech, audio, wearables and everyday electronics.', ''],
      ['jewelry', 'Jewelry', 'Chains, rings, bracelets and accessories that flex.', ''],
      ['shoes', 'Shoes', 'Kicks and sneakers to complete the fit.', ''],
      ['fragrances', 'Fragrances', 'Scents that leave a lasting impression.', ''],
    ];
    const ins = db.prepare('INSERT INTO categories (slug, name, description, image, sort_order) VALUES (?, ?, ?, ?, ?)');
    cats.forEach((c, i) => ins.run(...c, i));
    console.log('Seeded 4 categories.');
  }

  const userCount = db.prepare('SELECT COUNT(*) AS c FROM users').get().c;
  if (userCount === 0) {
    const admin = db.prepare(
      'INSERT INTO users (name, email, phone, password_hash, is_admin) VALUES (?, ?, ?, ?, 1)'
    );
    admin.run('TOUS CINO Admin', 'wasup1606@gmail.com', '+27677700019', bcrypt.hashSync('Admin@12345', 10));
    console.log('Seeded admin account  ->  email: wasup1606@gmail.com  |  password: Admin@12345');
  }

  const prodCount = db.prepare('SELECT COUNT(*) AS c FROM products').get().c;
  if (prodCount === 0) {
    console.log('Product catalogue is empty — add products from the admin dashboard (Products → Add product), or drop image files into public/images/products and use "Import new images from folder".');
  } else {
    console.log(`Products already present: ${prodCount}.`);
  }

  const couponCount = db.prepare('SELECT COUNT(*) AS c FROM coupons').get().c;
  if (couponCount === 0) {
    db.prepare('INSERT INTO coupons (code, type, value, min_subtotal, active) VALUES (?, ?, ?, ?, 1)').run(
      'TOUS10',
      'percent',
      10,
      0
    );
    console.log('Seeded demo coupon  ->  TOUS10 (10% off).');
  }

  const reviewCount = db.prepare('SELECT COUNT(*) AS c FROM reviews').get().c;
  if (reviewCount === 0) {
    const sample = [
      ['Thabo M.', 'Pretoria', 'The drip is insane', 'Ordered late at night and the team still confirmed within minutes. Quality is better than the photos. Definitely copping again.', 5],
      ['Lerato K.', 'Johannesburg', 'Fast delivery, real products', 'What you see is what you get. Shipping was quick and the packaging was clean. 10/10.', 5],
      ['Sipho N.', 'Centurion', 'Legit store', 'I was skeptical at first but the WhatsApp support made everything easy. Item matched exactly. Will recommend to the squad.', 4],
      ['Amahle D.', 'Soweto', 'My new favourite spot', 'The selection is different from the usual stores. Found something unique and it arrived in two days. Love it.', 5],
    ];
    const ins = db.prepare(
      'INSERT INTO reviews (product_id, name, city, title, body, rating, approved) VALUES (NULL, ?, ?, ?, ?, ?, 1)'
    );
    sample.forEach((r) => ins.run(...r));
    console.log('Seeded sample customer reviews (delete or manage them in Admin → Reviews).');
  }

  const tCount = db.prepare('SELECT COUNT(*) AS c FROM testimonials').get().c;
  if (tCount === 0) {
    const sample = [
      ['Thabo M.', 'Pretoria', 'Wireless earbuds', 'Delivered to my door in two days and the quality is unreal. Best online store I have used.', 5, ''],
      ['Lerato K.', 'Johannesburg', 'Gold chain set', 'The packaging was clean and the product matched the pictures perfectly. My new go-to store.', 5, ''],
      ['Sipho N.', 'Centurion', 'Sneaker collab', 'Support was quick on WhatsApp and the shoes arrived exactly as described. Highly recommend.', 5, ''],
      ['Amahle D.', 'Soweto', 'Perfume set', 'Smelled it and immediately fell in love. Fast delivery and great communication throughout.', 5, ''],
    ];
    const ins = db.prepare(
      'INSERT INTO testimonials (customer_name, location, product_name, text, rating, photo, approved, sort_order) VALUES (?, ?, ?, ?, ?, ?, 1, ?)'
    );
    sample.forEach((t, i) => ins.run(...t, i));
    console.log('Seeded sample testimonials (add customer photos in Admin → Testimonials).');
  }

  console.log('Categories:', categoriesList().map((c) => `${c.name} (${c.product_count})`).join(', '));
  console.log('Seed complete.');
}

run();
