const User = require('../models/users.model');
const Product = require('../models/product.model');
const Order = require('../models/order.model');
const Transaction = require('../models/transaction.model');
const { BadRequestError } = require('../core/error.response');
const { decrypt } = require('../utils/crypto');
const discountService = require('./discount.service');

class OrderService {
    async buyProduct(userId, productId, discountCode = null) {
        // 1. Check User
        const user = await User.findById(userId);
        if (!user) throw new BadRequestError('Người dùng không tồn tại');

        // 2. Check Product
        const product = await Product.findById(productId);
        if (!product) throw new BadRequestError('Sản phẩm không tồn tại');
        if (product.status !== 'available') throw new BadRequestError('Sản phẩm đã được bán hoặc đang bị khóa');

        // 3. Calculate price with discount
        let finalPrice = product.price;
        let discountAmount = 0;
        let appliedDiscount = null;

        if (discountCode) {
            appliedDiscount = await discountService.validateAndApplyDiscount(discountCode, userId, product.price);
            discountAmount = appliedDiscount.discountAmount;
            finalPrice = appliedDiscount.finalPrice;
        }

        // 4. Check Balance
        if (user.balance < finalPrice) {
            throw new BadRequestError('Số dư không đủ. Vui lòng nạp thêm tiền!');
        }

        // 5. Update Balance
        const balanceBefore = user.balance;
        user.balance -= finalPrice;
        await user.save();

        // 6. Update Product Status
        product.status = 'sold';
        await product.save();

        // 7. Mark discount as used
        if (appliedDiscount) {
            await discountService.markAsUsed(appliedDiscount.discountId, userId);
        }

        // 8. Create Order
        const order = await Order.create({
            userId,
            productId,
            price: finalPrice,
            originalPrice: product.price,
            discountCode: discountCode || null,
            discountAmount,
            status: 'completed',
        });

        // 9. Create Transaction Log
        await Transaction.create({
            userId,
            transCode: `BUY-${Math.random().toString(36).substring(2, 10).toUpperCase()}`,
            type: 'PURCHASE',
            amount: finalPrice,
            balanceBefore,
            balanceAfter: user.balance,
            content: discountCode
                ? `Mua tài khoản #${product.title} (Giảm ${discountAmount.toLocaleString('vi-VN')}đ)`
                : `Mua tài khoản #${product.title}`,
        });

        return {
            order,
            account: {
                username: decrypt(product.account.username),
                password: decrypt(product.account.password),
            },
            discount: appliedDiscount
                ? {
                      code: appliedDiscount.code,
                      discountAmount,
                      originalPrice: product.price,
                      finalPrice,
                  }
                : null,
        };
    }

    async getPurchaseHistory(userId) {
        const history = await Order.find({ userId }).populate('productId').sort({ createdAt: -1 });

        // Decrypt account info for history view
        return history.map((order) => {
            const orderObj = order.toObject();
            if (orderObj.productId && orderObj.productId.account) {
                orderObj.productId.account = {
                    username: decrypt(orderObj.productId.account.username),
                    password: decrypt(orderObj.productId.account.password),
                };
            }
            return orderObj;
        });
    }
}

module.exports = new OrderService();
