import 'dotenv/config';
import bcrypt from 'bcryptjs';
import { initDatabase, db } from './db.js';

await initDatabase();

const pairs = [
  { pair: 'BTCUSDT', name: 'Bitcoin / Tether' },
  { pair: 'ETHUSDT', name: 'Ethereum / Tether' },
  { pair: 'BNBUSDT', name: 'BNB / Tether' },
  { pair: 'SOLUSDT', name: 'Solana / Tether' },
  { pair: 'XRPUSDT', name: 'Ripple / Tether' },
  { pair: 'ADAUSDT', name: 'Cardano / Tether' },
  { pair: 'DOGEUSDT', name: 'Dogecoin / Tether' },
];

async function seed() {
  const existingUser = db.prepare('SELECT id FROM users WHERE email = ?').get('demo@signalpro.ir');
  if (!existingUser) {
    const hash = await bcrypt.hash('demo1234', 10);
    const expires = new Date();
    expires.setFullYear(expires.getFullYear() + 1);
    db.prepare(`
      INSERT INTO users (full_name, email, phone, password_hash, plan_months, subscription_expires_at, role)
      VALUES (?, ?, ?, ?, ?, ?, ?)
    `).run('علی رضایی', 'demo@signalpro.ir', '09121234567', hash, 12, expires.toISOString(), 'user');
    console.log('Demo user: demo@signalpro.ir / demo1234');
  }

  const count = db.prepare('SELECT COUNT(*) as c FROM signals').get().c;
  if (count > 0) {
    console.log(`Database already has ${count} signals. Skipping signal seed.`);
    return;
  }

  const insert = db.prepare(`
    INSERT INTO signals (pair, pair_name, type, status, result, sent_at, closed_at, last_update_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  `);

  const now = Date.now();
  let id = 1254;

  for (let i = 0; i < 7; i++) {
    const p = pairs[i % pairs.length];
    const sent = new Date(now - i * 3600000).toISOString();
    insert.run(p.pair, p.name, i % 2 === 0 ? 'BUY' : 'SELL', 'active', null, sent, null, sent);
  }

  for (let i = 0; i < 1200; i++) {
    const p = pairs[i % pairs.length];
    const isProfit = Math.random() > 0.31;
    const hoursAgo = Math.floor(Math.random() * 720) + 25;
    const duration = Math.floor(Math.random() * 8 + 1) * 3600000;
    const closed = new Date(now - hoursAgo * 3600000);
    const sent = new Date(closed.getTime() - duration);
    const isRecent = hoursAgo < 24;
    insert.run(
      p.pair,
      p.name,
      Math.random() > 0.5 ? 'BUY' : 'SELL',
      'closed',
      isProfit ? 'profit' : 'loss',
      sent.toISOString(),
      closed.toISOString(),
      closed.toISOString()
    );
    id--;
  }

  for (let i = 0; i < 5; i++) {
    const p = pairs[i % pairs.length];
    const closed = new Date(now - (i + 1) * 2 * 3600000);
    const sent = new Date(closed.getTime() - 3 * 3600000);
    insert.run(p.pair, p.name, 'BUY', 'closed', i % 2 === 0 ? 'profit' : 'loss', sent.toISOString(), closed.toISOString(), closed.toISOString());
  }

  console.log('Seeded signals successfully.');
}

seed().catch(console.error);
