"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.FavoriteService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("typeorm");
const typeorm_2 = require("@nestjs/typeorm");
const favorite_entity_1 = require("../../common/favorite/favorite.entity");
const shop_entity_1 = require("../../common/shop/shop.entity");
const review_entity_1 = require("../../common/review/review.entity");
const moment = require("moment");
const offer_entity_1 = require("../../common/offer/offer.entity");
const car_listing_entity_1 = require("../../common/carmarketplace/car-listing.entity");
const numberplate_listing_entity_1 = require("../../common/numberplate/numberplate-listing.entity");
let FavoriteService = class FavoriteService {
    constructor(favoriteRepository, shopRepository, reviewRepository, offerRepository, carListingRepository, plateListingRepository) {
        this.favoriteRepository = favoriteRepository;
        this.shopRepository = shopRepository;
        this.reviewRepository = reviewRepository;
        this.offerRepository = offerRepository;
        this.carListingRepository = carListingRepository;
        this.plateListingRepository = plateListingRepository;
    }
    async create(createFavoriteDto) {
        const favorite = this.favoriteRepository.create(createFavoriteDto);
        return this.favoriteRepository.save(favorite);
    }
    async findAll(shopId) {
        return this.favoriteRepository.find({
            where: { shopId },
        });
    }
    async findUserFavorite(userId) {
        const favoriteShops = await this.favoriteRepository.find({
            where: { userId },
        });
        const shopIds = favoriteShops.map(fav => fav.shopId);
        const shops = await this.shopRepository.find({
            where: { id: (0, typeorm_1.In)(shopIds) },
            order: { createdAt: 'DESC' },
            relations: ["schedules", "contact", "category"],
        });
        const today = moment().format('YYYY-MM-DD');
        const shopSummaryPromises = shops.map(async (shop) => {
            const favorite = favoriteShops.find(f => f.shopId === shop.id);
            const queryBuilder = this.offerRepository.createQueryBuilder('offer')
                .innerJoin('shop_offers', 'shopOffer', 'shopOffer.offerId = offer.id')
                .select([
                'offer.id AS offer_id',
                'offer.name AS offer_name',
                'offer.startDate AS start_date',
                'offer.endDate AS end_date',
                'offer.discount AS discount',
                'shopOffer.offer_discount AS offer_discount',
                'shopOffer.shopId AS shop_id'
            ])
                .where('shopOffer.shopId = :shopId', { shopId: shop.id })
                .andWhere('offer.startDate <= :today', { today })
                .andWhere('offer.endDate >= :today', { today });
            const offerSummary = await queryBuilder.getRawOne();
            const reviewSummary = await this.reviewRepository
                .createQueryBuilder('review')
                .select('AVG(review.rating)', 'averageRating')
                .addSelect('COUNT(review.id)', 'totalReviews')
                .where('review.shopId = :shopId', { shopId: shop.id })
                .getRawOne();
            return {
                favoriteId: favorite?.id ?? null,
                shop,
                reviewSummary: {
                    averageRating: reviewSummary.averageRating || 0,
                    totalReviews: reviewSummary.totalReviews || 0,
                },
                offer: offerSummary?.offer_discount || 0,
            };
        });
        return Promise.all(shopSummaryPromises);
    }
    async findOne(id) {
        const favorite = await this.favoriteRepository.findOneBy({ id });
        if (!favorite) {
            throw new common_1.NotFoundException(`Favorite with ID ${id} not found`);
        }
        return favorite;
    }
    async remove(id) {
        const result = await this.favoriteRepository.delete(id);
        if (result.affected === 0) {
            throw new common_1.NotFoundException(`Favorite with ID ${id} not found`);
        }
    }
    async addListingFavorite(userId, dto) {
        const existing = await this.favoriteRepository.findOneBy({
            userId,
            listingType: dto.listingType,
            listingId: dto.listingId,
        });
        if (existing) {
            throw new common_1.ConflictException("Already in favorites.");
        }
        const favorite = this.favoriteRepository.create({
            userId,
            listingType: dto.listingType,
            listingId: dto.listingId,
        });
        return this.favoriteRepository.save(favorite);
    }
    async removeListingFavorite(userId, listingType, listingId) {
        const result = await this.favoriteRepository.delete({ userId, listingType, listingId });
        if (result.affected === 0) {
            throw new common_1.NotFoundException("Favorite not found.");
        }
    }
    async checkListingFavorite(userId, listingType, listingId) {
        const favorite = await this.favoriteRepository.findOneBy({ userId, listingType, listingId });
        return { isFavorite: !!favorite, favoriteId: favorite?.id ?? null };
    }
    async findUserListingFavorites(userId, listingType) {
        const where = { userId };
        if (listingType)
            where.listingType = listingType;
        const favorites = await this.favoriteRepository.find({ where, order: { createdAt: "DESC" } });
        const carIds = favorites.filter(f => f.listingType === "car").map(f => f.listingId);
        const plateIds = favorites.filter(f => f.listingType === "plate").map(f => f.listingId);
        const [cars, plates] = await Promise.all([
            carIds.length ? this.carListingRepository.find({ where: { id: (0, typeorm_1.In)(carIds) } }) : Promise.resolve([]),
            plateIds.length ? this.plateListingRepository.find({ where: { id: (0, typeorm_1.In)(plateIds) } }) : Promise.resolve([]),
        ]);
        const carMap = new Map(cars.map(c => [c.id, c]));
        const plateMap = new Map(plates.map(p => [p.id, p]));
        return favorites.map(fav => ({
            favoriteId: fav.id,
            listingType: fav.listingType,
            listingId: fav.listingId,
            createdAt: fav.createdAt,
            listing: fav.listingType === "car"
                ? (carMap.get(fav.listingId) ?? null)
                : (plateMap.get(fav.listingId) ?? null),
        }));
    }
};
exports.FavoriteService = FavoriteService;
exports.FavoriteService = FavoriteService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_2.InjectRepository)(favorite_entity_1.Favorite)),
    __param(1, (0, typeorm_2.InjectRepository)(shop_entity_1.Shop)),
    __param(2, (0, typeorm_2.InjectRepository)(review_entity_1.Review)),
    __param(3, (0, typeorm_2.InjectRepository)(offer_entity_1.Offer)),
    __param(4, (0, typeorm_2.InjectRepository)(car_listing_entity_1.CarListing)),
    __param(5, (0, typeorm_2.InjectRepository)(numberplate_listing_entity_1.NumberPlateListing)),
    __metadata("design:paramtypes", [typeorm_1.Repository,
        typeorm_1.Repository,
        typeorm_1.Repository,
        typeorm_1.Repository,
        typeorm_1.Repository,
        typeorm_1.Repository])
], FavoriteService);
//# sourceMappingURL=favorite.service.js.map