"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCatalogSummary = exports.getCatalogues = exports.getPublishers = exports.getAuthors = exports.getCategories = void 0;
const database_1 = __importDefault(require("../config/database"));
const response_utils_1 = require("../utils/response.utils");
const pagination = (req) => {
    // The catalog currently has 1,072 authors. Allow a complete metadata list for
    // admin/public filters while still putting a hard ceiling on the response.
    const limit = Math.max(1, Math.min(2000, Number(req.query.limit) || 100));
    const page = Math.max(1, Number(req.query.page) || 1);
    return { limit, page, skip: (page - 1) * limit };
};
const getCategories = async (req, res) => {
    try {
        const { limit, page, skip } = pagination(req);
        const search = String(req.query.search ?? '').trim();
        const where = {
            ...(search ? { name: { contains: search } } : {}),
            ...(req.query.status === 'ALL' ? {} : { isActive: true }),
        };
        const [items, total] = await Promise.all([
            database_1.default.category.findMany({
                where,
                skip,
                take: limit,
                include: { _count: { select: { books: true } } },
                orderBy: [{ displayOrder: 'asc' }, { name: 'asc' }],
            }),
            database_1.default.category.count({ where }),
        ]);
        return (0, response_utils_1.sendSuccess)(res, 'Categories retrieved', {
            categories: items.map((item) => ({ ...item, productCount: item._count.books, _count: undefined })),
            pagination: { total, page, limit, totalPages: Math.max(1, Math.ceil(total / limit)) },
        });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to retrieve categories', error instanceof Error ? error.message : String(error), 500);
    }
};
exports.getCategories = getCategories;
const getAuthors = async (req, res) => {
    try {
        const { limit, page, skip } = pagination(req);
        const search = String(req.query.search ?? '').trim();
        const where = search ? { name: { contains: search } } : {};
        const [items, total] = await Promise.all([
            database_1.default.author.findMany({
                where,
                skip,
                take: limit,
                include: { _count: { select: { books: true } } },
                orderBy: { name: 'asc' },
            }),
            database_1.default.author.count({ where }),
        ]);
        return (0, response_utils_1.sendSuccess)(res, 'Authors retrieved', {
            authors: items.map((item) => ({ ...item, productCount: item._count.books, _count: undefined })),
            pagination: { total, page, limit, totalPages: Math.max(1, Math.ceil(total / limit)) },
        });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to retrieve authors', error instanceof Error ? error.message : String(error), 500);
    }
};
exports.getAuthors = getAuthors;
const getPublishers = async (req, res) => {
    try {
        const { limit, page, skip } = pagination(req);
        const search = String(req.query.search ?? '').trim();
        const where = search ? { name: { contains: search } } : {};
        const [items, total] = await Promise.all([
            database_1.default.publisher.findMany({
                where,
                skip,
                take: limit,
                include: { _count: { select: { books: true } } },
                orderBy: { name: 'asc' },
            }),
            database_1.default.publisher.count({ where }),
        ]);
        return (0, response_utils_1.sendSuccess)(res, 'Publishers retrieved', {
            publishers: items.map((item) => ({ ...item, productCount: item._count.books, _count: undefined })),
            pagination: { total, page, limit, totalPages: Math.max(1, Math.ceil(total / limit)) },
        });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to retrieve publishers', error instanceof Error ? error.message : String(error), 500);
    }
};
exports.getPublishers = getPublishers;
const getCatalogues = async (req, res) => {
    try {
        const search = String(req.query.search ?? '').trim();
        const catalogues = await database_1.default.catalogue.findMany({
            where: {
                ...(search ? { title: { contains: search } } : {}),
                ...(req.query.status === 'ALL' ? {} : { isActive: true }),
            },
            include: {
                categories: { include: { category: true } },
                _count: { select: { books: true } },
            },
            orderBy: { title: 'asc' },
        });
        return (0, response_utils_1.sendSuccess)(res, 'Catalogues retrieved', {
            catalogues: catalogues.map((catalogue) => ({
                id: catalogue.id,
                sourceCatalogueId: catalogue.sourceCatalogueId,
                title: catalogue.title,
                slug: catalogue.slug,
                pdfUrl: catalogue.pdfUrl,
                sourcePdfUrl: catalogue.sourcePdfUrl,
                assetStatus: catalogue.assetStatus,
                isActive: catalogue.isActive,
                productCount: catalogue._count.books,
                categories: catalogue.categories.map(({ category }) => ({
                    id: category.id,
                    name: category.name,
                    slug: category.slug,
                })),
            })),
        });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to retrieve catalogues', error instanceof Error ? error.message : String(error), 500);
    }
};
exports.getCatalogues = getCatalogues;
const getCatalogSummary = async (_req, res) => {
    try {
        const [products, categories, authors, publishers, attributes, catalogues, images] = await Promise.all([
            database_1.default.book.count({ where: { sourceProductId: { not: null } } }),
            database_1.default.category.count({ where: { sourceCategoryId: { not: null } } }),
            database_1.default.author.count({ where: { sourceKey: { not: null } } }),
            database_1.default.publisher.count({ where: { sourceKey: { not: null } } }),
            database_1.default.bookAttribute.count({ where: { book: { sourceProductId: { not: null } } } }),
            database_1.default.catalogue.count(),
            database_1.default.bookImage.count({ where: { book: { sourceProductId: { not: null } } } }),
        ]);
        return (0, response_utils_1.sendSuccess)(res, 'Catalog summary retrieved', {
            products,
            categories,
            authors,
            publishers,
            attributes,
            catalogues,
            images,
        });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to retrieve catalog summary', error instanceof Error ? error.message : String(error), 500);
    }
};
exports.getCatalogSummary = getCatalogSummary;
//# sourceMappingURL=catalog.controller.js.map