"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);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PricingDetailService = void 0;
const common_1 = require("@nestjs/common");
const prisma_service_1 = require("../prisma/prisma.service");
const client_1 = require("../../generated/prisma/client");
const bootstrap_table_response_dto_1 = require("../commons/dto/bootstrap-table-response.dto");
const prisma_query_builder_1 = require("../commons/utils/prisma-query-builder");
let PricingDetailService = class PricingDetailService {
    constructor(prisma) {
        this.prisma = prisma;
    }
    async findAll(query, headerId, itemTypeId) {
        const allowedFilters = {
            unit: 'string',
            status: 'enum',
            beginEffective: 'dateRange',
            endEffective: 'dateRange',
        };
        const where = (0, prisma_query_builder_1.buildWhereClause)(query, allowedFilters, []);
        if (headerId)
            where.headerId = headerId;
        if (itemTypeId)
            where.itemTypeId = itemTypeId;
        const allowedSortColumns = [
            'pricePerUnit',
            'weight',
            'unit',
            'status',
            'beginEffective',
            'endEffective',
            'createdAt',
        ];
        const orderBy = {};
        if (query.sort && allowedSortColumns.includes(query.sort)) {
            orderBy[query.sort] = query.sortOrder;
        }
        else {
            orderBy.beginEffective = 'desc';
        }
        const [total, rows] = await this.prisma.$transaction([
            this.prisma.pricingDetail.count({ where }),
            this.prisma.pricingDetail.findMany({
                where,
                skip: query.skip,
                take: query.take,
                orderBy,
                include: {
                    header: true,
                    itemType: true,
                },
            }),
        ]);
        return new bootstrap_table_response_dto_1.BootstrapTableResponseDto(total, rows);
    }
    async findOne(id) {
        const detail = await this.prisma.pricingDetail.findUnique({
            where: { id },
            include: { header: true, itemType: true },
        });
        if (!detail)
            throw new common_1.NotFoundException(`PricingDetail with id ${id} not found`);
        return detail;
    }
    async findActiveByHeader(headerId) {
        const now = new Date();
        const detail = await this.prisma.pricingDetail.findFirst({
            where: {
                headerId,
                status: client_1.SettingStatus.ACTIVE,
                beginEffective: { lte: now },
                OR: [{ endEffective: null }, { endEffective: { gte: now } }],
            },
            orderBy: { beginEffective: 'desc' },
            include: { header: true, itemType: true },
        });
        if (!detail)
            throw new common_1.NotFoundException(`No active pricing found for header ${headerId}`);
        return detail;
    }
    async create(dto) {
        return this.prisma.pricingDetail.create({
            data: {
                ...dto,
                beginEffective: new Date(dto.beginEffective),
                endEffective: dto.endEffective ? new Date(dto.endEffective) : null,
            },
            include: { header: true, itemType: true },
        });
    }
    async update(id, dto) {
        await this.findOne(id);
        return this.prisma.pricingDetail.update({
            where: { id },
            data: {
                ...dto,
                ...(dto.beginEffective ? { beginEffective: new Date(dto.beginEffective) } : {}),
                ...(dto.endEffective ? { endEffective: new Date(dto.endEffective) } : {}),
            },
            include: { header: true, itemType: true },
        });
    }
    async updatePrice(headerId, dto) {
        const now = new Date();
        const currentActive = await this.prisma.pricingDetail.findFirst({
            where: {
                headerId,
                status: client_1.SettingStatus.ACTIVE,
                OR: [{ endEffective: null }, { endEffective: { gte: now } }],
            },
            orderBy: { beginEffective: 'desc' },
        });
        if (!currentActive)
            throw new common_1.NotFoundException(`No active pricing found for header ${headerId}`);
        const beginEffectiveDate = new Date(dto.beginEffective);
        await this.prisma.pricingDetail.update({
            where: { id: currentActive.id },
            data: { endEffective: beginEffectiveDate, status: client_1.SettingStatus.INACTIVE },
        });
        return this.prisma.pricingDetail.create({
            data: {
                headerId,
                itemTypeId: currentActive.itemTypeId,
                pricePerUnit: dto.pricePerUnit,
                weight: currentActive.weight,
                unit: currentActive.unit,
                status: client_1.SettingStatus.ACTIVE,
                beginEffective: beginEffectiveDate,
                endEffective: null,
                createdBy: dto.modifiedBy,
                modifiedBy: dto.modifiedBy,
            },
            include: { header: true, itemType: true },
        });
    }
    async remove(id) {
        await this.findOne(id);
        return this.prisma.pricingDetail.delete({ where: { id } });
    }
};
exports.PricingDetailService = PricingDetailService;
exports.PricingDetailService = PricingDetailService = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [prisma_service_1.PrismaService])
], PricingDetailService);
//# sourceMappingURL=pricing-detail.service.js.map