import { Router } from 'express';
import multer from 'multer';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
import { db, PLAN_PRICES } from '../db.js';
import { authMiddleware } from '../middleware/auth.js';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const uploadDir = path.join(__dirname, '..', '..', 'uploads', 'receipts');
fs.mkdirSync(uploadDir, { recursive: true });

const storage = multer.diskStorage({
  destination: uploadDir,
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname);
    cb(null, `receipt-${req.user.id}-${Date.now()}${ext}`);
  },
});
const upload = multer({
  storage,
  limits: { fileSize: 5 * 1024 * 1024 },
  fileFilter: (req, file, cb) => {
    const allowed = /\.(jpg|jpeg|png|pdf)$/i;
    if (allowed.test(file.originalname)) cb(null, true);
    else cb(new Error('فرمت فایل مجاز نیست'));
  },
});

const router = Router();

router.get('/plans', (req, res) => {
  const plans = Object.entries(PLAN_PRICES).map(([key, p]) => ({
    months: p.months,
    originalPrice: p.price,
    discountPercent: p.discount,
    finalPrice: p.price - Math.round((p.price * p.discount) / 100),
  }));
  res.json({ plans });
});

router.use(authMiddleware);

router.get('/', (req, res) => {
  const rows = db.prepare(`
    SELECT id, plan_months, original_price, discount_percent, final_price, receipt_path, status, created_at
    FROM payments WHERE user_id = ? ORDER BY created_at DESC
  `).all(req.user.id);
  res.json({
    payments: rows.map((r) => ({
      id: r.id,
      planMonths: r.plan_months,
      originalPrice: r.original_price,
      discountPercent: r.discount_percent,
      finalPrice: r.final_price,
      receiptPath: r.receipt_path,
      status: r.status,
      createdAt: r.created_at,
    })),
  });
});

router.post('/receipt', upload.single('receipt'), (req, res) => {
  if (!req.file) return res.status(400).json({ error: 'فایل ارسال نشد' });
  const payment = db.prepare(`
    SELECT id FROM payments WHERE user_id = ? ORDER BY id DESC LIMIT 1
  `).get(req.user.id);
  if (!payment) return res.status(404).json({ error: 'پرداختی یافت نشد' });

  db.prepare('UPDATE payments SET receipt_path = ? WHERE id = ?').run(req.file.filename, payment.id);
  res.json({ message: 'فیش با موفقیت آپلود شد', filename: req.file.filename });
});

export default router;
