"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteBentoItem = exports.updateBentoItem = exports.createBentoItem = exports.getBentoItems = void 0;
const client_1 = require("@prisma/client");
const apiError_1 = __importDefault(require("../../utils/apiError"));
const r2_1 = require("../../utils/r2");
const prisma = new client_1.PrismaClient();
// GET /api/admin/bento
const getBentoItems = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const items = yield prisma.featuredCategory.findMany({
            include: {
                category: {
                    select: { name: true, image: true }
                }
            },
            orderBy: { order: 'asc' }
        });
        const formatted = items.map(item => {
            var _a, _b;
            return ({
                id: item.id,
                categoryName: ((_a = item.category) === null || _a === void 0 ? void 0 : _a.name) || "Unknown Category",
                // Priority: Custom Image -> Category Image -> Placeholder
                image: item.customImage || ((_b = item.category) === null || _b === void 0 ? void 0 : _b.image) || '/placeholder-category.jpg',
                size: item.size,
                active: item.active,
                order: item.order,
                categoryId: item.categoryId,
                customImage: item.customImage // Include for edit form
            });
        });
        res.json(formatted);
    }
    catch (error) {
        console.error("Get Bento Error:", error);
        res.status(500).json({ error: "Failed to fetch grid items" });
    }
});
exports.getBentoItems = getBentoItems;
// POST /api/admin/bento
const createBentoItem = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { categoryId, size, order, active } = req.body;
        if (!categoryId) {
            return res.status(400).json({ error: "Category is required" });
        }
        const image = req.file;
        if (!image) {
            throw new apiError_1.default(false, 400, "Images is required");
        }
        const uploadedImg = yield (0, r2_1.uploadFileToR2)(image);
        if (!uploadedImg.url) {
            throw new apiError_1.default(false, 400, "Image Upload to R2 Fail");
        }
        const newItem = yield prisma.featuredCategory.create({
            data: {
                categoryId,
                size: size || 'small',
                customImage: uploadedImg.url,
                order: parseInt(order) || 0,
                active: active === "true"
            }
        });
        res.status(201).json(newItem);
    }
    catch (error) {
        console.error("Create Bento Error:", error);
        res.status(500).json({ error: "Failed to create grid item" });
    }
});
exports.createBentoItem = createBentoItem;
// PUT /api/admin/bento/:id
const updateBentoItem = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { id } = req.params;
        const { categoryId, size, customImage, order, active } = req.body;
        const updated = yield prisma.featuredCategory.update({
            where: { id },
            data: {
                categoryId,
                size,
                customImage,
                order: parseInt(order),
                active: active === "true",
            }
        });
        res.json(updated);
    }
    catch (error) {
        res.status(500).json({ error: "Failed to update grid item" });
    }
});
exports.updateBentoItem = updateBentoItem;
// DELETE /api/admin/bento/:id
const deleteBentoItem = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { id } = req.params;
        yield prisma.featuredCategory.delete({ where: { id } });
        res.json({ message: "Item deleted" });
    }
    catch (error) {
        res.status(500).json({ error: "Failed to delete item" });
    }
});
exports.deleteBentoItem = deleteBentoItem;
