import { prisma } from "../../core/prisma";
import { AppError } from "../../core/AppError";

export const categoryService = {
    findAll(shopId: string) {
        return prisma.category.findMany({
            where: {
                shopId,
                active: true
            },
            orderBy: {
                displayOrder: "asc"
            }
        });
    },

    findById(shopId: string, id: string) {
        return prisma.category.findFirst({
            where: {
                id,
                shopId
            }
        });
    },

    create(shopId: string, data: any) {
        return prisma.category.create({
            data: {
                ...data,
                shopId
            }
        });
    },

    update(shopId: string, id: string, data: any) {
        return prisma.category.updateMany({
            where: {
                id,
                shopId
            },
            data
        });
    },

    /**
     * Bulk-update displayOrder for a list of category IDs.
     * orderedIds[0] gets displayOrder 0, orderedIds[1] gets 1, etc.
     */
    async reorder(shopId: string, orderedIds: string[]) {
        const updates = orderedIds.map((id, index) =>
            prisma.category.updateMany({
                where: { id, shopId },
                data: { displayOrder: index }
            })
        );
        await prisma.$transaction(updates);
    },

    async softDelete(shopId: string, id: string) {
        const usedByProducts = await prisma.product.count({
            where: {
                shopId,
                categoryId: id,
                active: true
            }
        })

        if (usedByProducts > 0) {
            throw new AppError(
                `Impossible de supprimer cette catégorie: ${usedByProducts} produit(s) l'utilisent encore.`,
                409
            )
        }

        return prisma.category.updateMany({
            where: {
                id,
                shopId
            },
            data: {
                active: false
            }
        });
    }
};