const ProductService = require('../services/product.service');

const { BadRequestError } = require('../core/error.response');
const { OK, Created } = require('../core/success.response');

class ProductController {
    createProduct = async (req, res, next) => {
        const { uploadMultiple } = require('../config/cloudinaryUpload');
        const images = await uploadMultiple(req.files, 'products');
        const { categoryId, price, description, account, info } = req.body;

        if (!categoryId || !price || !account || !images) {
            throw new BadRequestError('Bạn đang thiếu thông tin !');
        }

        // Account comes as JSON string from FormData
        let parsedAccount = account;
        if (typeof account === 'string') {
            try {
                parsedAccount = JSON.parse(account);
            } catch (e) {
                throw new BadRequestError('Dữ liệu tài khoản không hợp lệ!');
            }
        }

        // Generate unique 8-digit title
        const generateUniqueTitle = async () => {
            let title;
            let isUnique = false;
            while (!isUnique) {
                // Generate random 8-digit number (10000000 - 99999999)
                title = Math.floor(10000000 + Math.random() * 90000000).toString();
                // Check if title already exists
                const existing = await ProductService.findByTitle(title);
                if (!existing) {
                    isUnique = true;
                }
            }
            return title;
        };

        const title = await generateUniqueTitle();

        // Parse info from JSON string (FormData)
        let parsedInfo = info;
        if (typeof info === 'string') {
            try {
                parsedInfo = JSON.parse(info);
            } catch (e) {
                parsedInfo = {};
            }
        }

        const product = await ProductService.createProduct({
            title,
            categoryId,
            price,
            description,
            account: parsedAccount,
            images,
            info: parsedInfo,
        });
        return new Created({
            message: 'Tạo sản phẩm thành công !',
            metadata: product,
        }).send(res);
    };

    updateProduct = async (req, res, next) => {
        const { id } = req.params;
        const { uploadMultiple } = require('../config/cloudinaryUpload');
        const images = req.files ? await uploadMultiple(req.files, 'products') : [];
        const { title, categoryId, price, description, account, status, oldImages, info } = req.body;

        // Account comes as string due to FormData
        let parsedAccount = account;
        if (typeof account === 'string') {
            try {
                parsedAccount = JSON.parse(account);
            } catch (e) {
                parsedAccount = {};
            }
        }

        // Parse oldImages (images to keep)
        let parsedOldImages = [];
        if (typeof oldImages === 'string') {
            try {
                parsedOldImages = JSON.parse(oldImages);
            } catch (e) {
                parsedOldImages = [];
            }
        }

        // Parse info from JSON string (FormData)
        let parsedInfo = info;
        if (typeof info === 'string') {
            try {
                parsedInfo = JSON.parse(info);
            } catch (e) {
                parsedInfo = {};
            }
        }

        const product = await ProductService.updateProduct({
            id,
            title,
            categoryId,
            price,
            description,
            account: parsedAccount,
            images,
            oldImages: parsedOldImages,
            status,
            info: parsedInfo,
        });

        return new OK({
            message: 'Cập nhật sản phẩm thành công !',
            metadata: product,
        }).send(res);
    };

    deleteProduct = async (req, res, next) => {
        const { id } = req.params;
        await ProductService.deleteProduct(id);
        return new OK({
            message: 'Xóa sản phẩm thành công !',
            metadata: true,
        }).send(res);
    };

    getAllProduct = async (req, res, next) => {
        const products = await ProductService.getAllProduct();
        return new OK({
            message: 'Lấy danh sách sản phẩm thành công !',
            metadata: products,
        }).send(res);
    };

    getProductByCategory = async (req, res, next) => {
        const { categoryId } = req.params;
        const { minPrice, maxPrice, sortBy, search, page, limit } = req.query;

        const result = await ProductService.getProductByCategory(categoryId, {
            minPrice,
            maxPrice,
            sortBy,
            search,
            page,
            limit,
        });

        return new OK({
            message: 'Lấy danh sách sản phẩm thành công !',
            metadata: result.products,
            pagination: result.pagination,
        }).send(res);
    };

    getProductById = async (req, res, next) => {
        const { id } = req.params;
        const product = await ProductService.getProductById(id);
        if (!product) {
            throw new BadRequestError('Sản phẩm không tồn tại!');
        }
        return new OK({
            message: 'Lấy thông tin sản phẩm thành công !',
            metadata: product,
        }).send(res);
    };
}

module.exports = new ProductController();
