"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DashboardService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const category_entity_1 = require("../../common/category/category.entity");
const offer_entity_1 = require("../../common/offer/offer.entity");
const plan_entity_1 = require("../../common/plan/plan.entity");
const review_entity_1 = require("../../common/review/review.entity");
const shop_entity_1 = require("../../common/shop/shop.entity");
const user_entity_1 = require("../../common/vendor/user.entity");
const vendor_entity_1 = require("../../common/vendor/vendor.entity");
const vendor_plan_entity_1 = require("../../common/vendor/vendor_plan.entity");
const typeorm_2 = require("typeorm");
let DashboardService = class DashboardService {
    constructor(userRepo, shopRepo, offerRepo, reviewRepo, categoryRepo, vendorRepo, vendorPlanRepo) {
        this.userRepo = userRepo;
        this.shopRepo = shopRepo;
        this.offerRepo = offerRepo;
        this.reviewRepo = reviewRepo;
        this.categoryRepo = categoryRepo;
        this.vendorRepo = vendorRepo;
        this.vendorPlanRepo = vendorPlanRepo;
    }
    async getFullDashboard(recentLimit = 20, topDays = 7, topLimit = 10) {
        const [totalUserCount, totalVendorCount, totalShopCount, totalOfferCount, recentVendors, topRatedShops,] = await Promise.all([
            this.userRepo.createQueryBuilder('u').getCount(),
            this.vendorRepo.createQueryBuilder('v').getCount(),
            this.shopRepo.createQueryBuilder('s').getCount(),
            this.offerRepo.createQueryBuilder('o')
                .where('o.status = :status', { status: 'active' })
                .getCount(),
            this.getRecentVendors(recentLimit),
            (async () => {
                const ratingsAgg = this.reviewRepo
                    .createQueryBuilder('r')
                    .select('r.shopId', 'shopId')
                    .addSelect('AVG(r.rating)', 'avgRating')
                    .addSelect('COUNT(r.id)', 'ratingCount')
                    .where('r.createdAt >= DATE_SUB(NOW(), INTERVAL :days DAY)', { days: topDays })
                    .groupBy('r.shopId');
                const qb = this.shopRepo.createQueryBuilder('s')
                    .select(['s.id AS shopId', 's.name AS shopName'])
                    .addSelect('c.name', 'categoryName')
                    .addSelect('u.name', 'vendorName')
                    .addSelect('agg.avgRating', 'avgRating')
                    .addSelect('agg.ratingCount', 'ratingCount')
                    .innerJoin(`(${ratingsAgg.getQuery()})`, 'agg', 'agg.shopId = s.id')
                    .leftJoin('s.category', 'c')
                    .leftJoin('s.user', 'u')
                    .orderBy('agg.avgRating', 'DESC')
                    .addOrderBy('agg.ratingCount', 'DESC')
                    .limit(topLimit);
                qb.setParameters(ratingsAgg.getParameters());
                return qb.getRawMany();
            })(),
        ]);
        return {
            totalUserCount,
            totalVendorCount,
            totalShopCount,
            totalOfferCount,
            recentVendors,
            topRatedShops,
        };
    }
    async getRecentVendors(recentLimit) {
        const qb = this.userRepo
            .createQueryBuilder('user')
            .leftJoinAndMapOne('user.vendorPlan', vendor_plan_entity_1.VendorPlan, 'vendorPlan', 'vendorPlan.vendorId = user.id')
            .leftJoinAndMapOne('vendorPlan.plan', plan_entity_1.Plan, 'plan', 'plan.id = vendorPlan.planId')
            .leftJoinAndSelect('user.vendor', 'vendor')
            .where('user.roles LIKE :role', { role: `%${user_entity_1.UserRole.VENDOR}%` })
            .orderBy(`GREATEST(
           COALESCE(vendorPlan.updatedAt, '1970-01-01 00:00:00'),
           COALESCE(vendorPlan.createdAt, '1970-01-01 00:00:00')
         )`, 'DESC')
            .addOrderBy('vendorPlan.updatedAt', 'DESC')
            .addOrderBy('user.createdAt', 'DESC');
        if (typeof recentLimit === 'number' && recentLimit > 0) {
            qb.limit(recentLimit);
        }
        return qb.getMany();
    }
};
exports.DashboardService = DashboardService;
exports.DashboardService = DashboardService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(user_entity_1.User)),
    __param(1, (0, typeorm_1.InjectRepository)(shop_entity_1.Shop)),
    __param(2, (0, typeorm_1.InjectRepository)(offer_entity_1.Offer)),
    __param(3, (0, typeorm_1.InjectRepository)(review_entity_1.Review)),
    __param(4, (0, typeorm_1.InjectRepository)(category_entity_1.Category)),
    __param(5, (0, typeorm_1.InjectRepository)(vendor_entity_1.Vendor)),
    __param(6, (0, typeorm_1.InjectRepository)(vendor_plan_entity_1.VendorPlan)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        typeorm_2.Repository,
        typeorm_2.Repository,
        typeorm_2.Repository,
        typeorm_2.Repository,
        typeorm_2.Repository,
        typeorm_2.Repository])
], DashboardService);
//# sourceMappingURL=dashboard.service.js.map