import { Router } from 'express';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import { db, PLAN_PRICES } from '../db.js';
import { authMiddleware } from '../middleware/auth.js';

const router = Router();

function generateOtp() {
  return String(Math.floor(100000 + Math.random() * 900000));
}

function addMonths(date, months) {
  const d = new Date(date);
  d.setMonth(d.getMonth() + months);
  return d.toISOString();
}

router.post('/register', async (req, res) => {
  try {
    const { fullName, phone, email, password, planMonths = 12, affiliateCode } = req.body;
    if (!fullName || !email || !password) {
      return res.status(400).json({ error: 'فیلدهای الزامی را پر کنید' });
    }
    const existing = db.prepare('SELECT id FROM users WHERE email = ?').get(email);
    if (existing) return res.status(400).json({ error: 'این ایمیل قبلاً ثبت شده' });

    const plan = PLAN_PRICES[planMonths] || PLAN_PRICES[12];
    const discountAmount = Math.round((plan.price * plan.discount) / 100);
    const finalPrice = plan.price - discountAmount;

    const hash = await bcrypt.hash(password, 10);
    const expires = addMonths(new Date(), plan.months);

    const result = db.prepare(`
      INSERT INTO users (full_name, email, phone, password_hash, plan_months, subscription_expires_at, affiliate_code)
      VALUES (?, ?, ?, ?, ?, ?, ?)
    `).run(fullName, email, phone || null, hash, plan.months, expires, affiliateCode || null);

    const userId = result.lastInsertRowid;
    db.prepare(`
      INSERT INTO payments (user_id, plan_months, original_price, discount_percent, final_price, status)
      VALUES (?, ?, ?, ?, ?, 'pending')
    `).run(userId, plan.months, plan.price, plan.discount, finalPrice);

    res.status(201).json({
      message: 'ثبت‌نام موفق. لطفاً فیش پرداخت را آپلود کنید.',
      userId,
      pricing: { originalPrice: plan.price, discountPercent: plan.discount, finalPrice },
    });
  } catch (e) {
    res.status(500).json({ error: e.message });
  }
});

router.post('/login', async (req, res) => {
  try {
    const { email, password } = req.body;
    const user = db.prepare('SELECT * FROM users WHERE email = ?').get(email);
    if (!user) return res.status(401).json({ error: 'ایمیل یا رمز عبور اشتباه است' });

    const valid = await bcrypt.compare(password, user.password_hash);
    if (!valid) return res.status(401).json({ error: 'ایمیل یا رمز عبور اشتباه است' });

    const code = generateOtp();
    const expires = new Date(Date.now() + (Number(process.env.OTP_EXPIRY_MINUTES) || 10) * 60000).toISOString();
    db.prepare('INSERT INTO otp_codes (email, code, expires_at) VALUES (?, ?, ?)').run(email, code, expires);

    console.log(`[OTP] ${email}: ${code}`);

    res.json({ message: 'کد تأیید به ایمیل ارسال شد', requiresOtp: true, email });
  } catch (e) {
    res.status(500).json({ error: e.message });
  }
});

router.post('/verify-otp', (req, res) => {
  try {
    const { email, code } = req.body;
    const otp = db.prepare(`
      SELECT * FROM otp_codes WHERE email = ? AND code = ? AND used = 0
      ORDER BY id DESC LIMIT 1
    `).get(email, code);

    if (!otp) return res.status(400).json({ error: 'کد نامعتبر است' });
    if (new Date(otp.expires_at) < new Date()) {
      return res.status(400).json({ error: 'کد منقضی شده است' });
    }

    db.prepare('UPDATE otp_codes SET used = 1 WHERE id = ?').run(otp.id);
    const user = db.prepare('SELECT * FROM users WHERE email = ?').get(email);
    const token = jwt.sign(
      { id: user.id, email: user.email, role: user.role },
      process.env.JWT_SECRET || 'signalpro-dev-secret-change-in-production',
      { expiresIn: '7d' }
    );

    res.json({
      token,
      user: {
        id: user.id,
        fullName: user.full_name,
        email: user.email,
        phone: user.phone,
        planMonths: user.plan_months,
        subscriptionExpiresAt: user.subscription_expires_at,
        role: user.role,
      },
    });
  } catch (e) {
    res.status(500).json({ error: e.message });
  }
});

router.post('/resend-otp', (req, res) => {
  const { email } = req.body;
  const user = db.prepare('SELECT id FROM users WHERE email = ?').get(email);
  if (!user) return res.status(404).json({ error: 'کاربر یافت نشد' });

  const code = generateOtp();
  const expires = new Date(Date.now() + 10 * 60000).toISOString();
  db.prepare('INSERT INTO otp_codes (email, code, expires_at) VALUES (?, ?, ?)').run(email, code, expires);
  console.log(`[OTP] ${email}: ${code}`);
  res.json({ message: 'کد جدید ارسال شد' });
});

router.get('/me', authMiddleware, (req, res) => {
  const user = db.prepare('SELECT id, full_name, email, phone, plan_months, subscription_expires_at, role FROM users WHERE id = ?').get(req.user.id);
  if (!user) return res.status(404).json({ error: 'کاربر یافت نشد' });
  res.json({
    id: user.id,
    fullName: user.full_name,
    email: user.email,
    phone: user.phone,
    planMonths: user.plan_months,
    subscriptionExpiresAt: user.subscription_expires_at,
    role: user.role,
  });
});

export default router;
