"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.applyCouponCode = exports.deleteCoupon = exports.updateCoupon = exports.createCoupon = exports.getCoupons = void 0;
const database_1 = __importDefault(require("../config/database"));
const response_utils_1 = require("../utils/response.utils");
// 1. List all coupons
const getCoupons = async (req, res) => {
    try {
        const coupons = await database_1.default.coupon.findMany({
            orderBy: { createdAt: 'desc' },
        });
        return (0, response_utils_1.sendSuccess)(res, 'Coupons retrieved successfully', { coupons });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to fetch coupons', error.message, 500);
    }
};
exports.getCoupons = getCoupons;
// 2. Create a new coupon
const createCoupon = async (req, res) => {
    try {
        const { code, discountType, discountValue, minOrderValue, maxDiscount, usageLimit, expiresAt, isActive } = req.body;
        const existing = await database_1.default.coupon.findUnique({ where: { code: code.toUpperCase() } });
        if (existing)
            return (0, response_utils_1.sendError)(res, 'Coupon code already exists', null, 400);
        const coupon = await database_1.default.coupon.create({
            data: {
                code: code.toUpperCase(),
                discountType, // e.g. PERCENTAGE, FIXED_AMOUNT
                discountValue: Number(discountValue),
                minOrderValue: minOrderValue ? Number(minOrderValue) : null,
                maxDiscount: maxDiscount ? Number(maxDiscount) : null,
                usageLimit: usageLimit ? parseInt(usageLimit) : null,
                expiresAt: new Date(expiresAt),
                isActive: isActive ?? true,
            },
        });
        return (0, response_utils_1.sendSuccess)(res, 'Coupon created successfully', { coupon });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to create coupon', error.message, 500);
    }
};
exports.createCoupon = createCoupon;
// 3. Edit coupon settings
const updateCoupon = async (req, res) => {
    try {
        const { id } = req.params;
        const { code, discountType, discountValue, minOrderValue, maxDiscount, usageLimit, expiresAt, isActive } = req.body;
        const coupon = await database_1.default.coupon.findUnique({ where: { id } });
        if (!coupon)
            return (0, response_utils_1.sendError)(res, 'Coupon not found', null, 404);
        const updated = await database_1.default.coupon.update({
            where: { id },
            data: {
                code: code ? code.toUpperCase() : undefined,
                discountType,
                discountValue: discountValue ? Number(discountValue) : undefined,
                minOrderValue: minOrderValue !== undefined ? (minOrderValue ? Number(minOrderValue) : null) : undefined,
                maxDiscount: maxDiscount !== undefined ? (maxDiscount ? Number(maxDiscount) : null) : undefined,
                usageLimit: usageLimit !== undefined ? (usageLimit ? parseInt(usageLimit) : null) : undefined,
                expiresAt: expiresAt ? new Date(expiresAt) : undefined,
                isActive: isActive !== undefined ? isActive : undefined,
            },
        });
        return (0, response_utils_1.sendSuccess)(res, 'Coupon updated successfully', { coupon: updated });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to update coupon', error.message, 500);
    }
};
exports.updateCoupon = updateCoupon;
// 4. Delete coupon
const deleteCoupon = async (req, res) => {
    try {
        const { id } = req.params;
        await database_1.default.coupon.delete({ where: { id } });
        return (0, response_utils_1.sendSuccess)(res, 'Coupon deleted successfully');
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to delete coupon', error.message, 500);
    }
};
exports.deleteCoupon = deleteCoupon;
// 5. Apply coupon logic (checking limits, expiries, usage limits)
const applyCouponCode = async (req, res) => {
    try {
        const { code, orderAmount } = req.body;
        const coupon = await database_1.default.coupon.findUnique({
            where: { code: code.toUpperCase() },
        });
        if (!coupon || !coupon.isActive) {
            return (0, response_utils_1.sendError)(res, 'Invalid or inactive coupon code', null, 400);
        }
        const now = new Date();
        if (coupon.expiresAt && now > coupon.expiresAt) {
            return (0, response_utils_1.sendError)(res, 'Coupon has expired', null, 400);
        }
        if (coupon.minOrderValue && Number(orderAmount) < Number(coupon.minOrderValue)) {
            return (0, response_utils_1.sendError)(res, `Minimum order amount of ₹${coupon.minOrderValue} required`, null, 400);
        }
        if (coupon.usageLimit && coupon.usageCount >= coupon.usageLimit) {
            return (0, response_utils_1.sendError)(res, 'Coupon usage limit has been reached', null, 400);
        }
        // Calculate discount value
        let discount = 0;
        if (coupon.discountType === 'PERCENTAGE') {
            discount = (Number(orderAmount) * Number(coupon.discountValue)) / 100;
            if (coupon.maxDiscount && discount > Number(coupon.maxDiscount)) {
                discount = Number(coupon.maxDiscount);
            }
        }
        else {
            discount = Number(coupon.discountValue);
        }
        return (0, response_utils_1.sendSuccess)(res, 'Coupon applied successfully', {
            code: coupon.code,
            discount,
            discountType: coupon.discountType,
            discountValue: coupon.discountValue,
        });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to apply coupon code', error.message, 500);
    }
};
exports.applyCouponCode = applyCouponCode;
//# sourceMappingURL=coupon.controller.js.map