"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.PricingHeaderService = void 0;
const common_1 = require("@nestjs/common");
const prisma_service_1 = require("../prisma/prisma.service");
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 PricingHeaderService = class PricingHeaderService {
    constructor(prisma) {
        this.prisma = prisma;
    }
    async findAll(query, itemTypeId) {
        const allowedFilters = {
            code: 'string',
            name: 'string',
            status: 'enum',
            unit: 'string',
            effectiveDate: 'dateRange',
        };
        const where = (0, prisma_query_builder_1.buildWhereClause)(query, allowedFilters, ['code', 'name']);
        if (itemTypeId) {
            where.itemTypeId = itemTypeId;
        }
        const allowedSortColumns = ['code', 'name', 'weight', 'unit', 'status', 'effectiveDate', 'createdAt'];
        const orderBy = {};
        if (query.sort && allowedSortColumns.includes(query.sort)) {
            orderBy[query.sort] = query.sortOrder;
        }
        else {
            orderBy.createdAt = 'desc';
        }
        const [total, headers] = await this.prisma.$transaction([
            this.prisma.pricingHeader.count({ where }),
            this.prisma.pricingHeader.findMany({
                where,
                skip: query.skip,
                take: query.take,
                orderBy,
                include: { itemType: true },
            }),
        ]);
        const now = new Date();
        const rows = await Promise.all(headers.map(async (header) => {
            const activePrice = await this.prisma.pricingDetail.findFirst({
                where: {
                    headerId: header.id,
                    status: 'ACTIVE',
                    beginEffective: { lte: now },
                    OR: [{ endEffective: null }, { endEffective: { gte: now } }],
                },
                orderBy: { beginEffective: 'desc' },
                select: {
                    id: true,
                    pricePerUnit: true,
                    beginEffective: true,
                },
            });
            return { ...header, activePrice };
        }));
        return new bootstrap_table_response_dto_1.BootstrapTableResponseDto(total, rows);
    }
    async findOne(id) {
        const header = await this.prisma.pricingHeader.findUnique({
            where: { id },
            include: {
                itemType: true,
                pricingDetails: {
                    orderBy: { beginEffective: 'desc' },
                },
            },
        });
        if (!header)
            throw new common_1.NotFoundException(`PricingHeader with id ${id} not found`);
        return header;
    }
    async create(dto) {
        const existing = await this.prisma.pricingHeader.findUnique({
            where: { code: dto.code },
        });
        if (existing)
            throw new common_1.ConflictException(`Code "${dto.code}" already exists`);
        return this.prisma.pricingHeader.create({
            data: {
                ...dto,
                effectiveDate: new Date(dto.effectiveDate),
            },
            include: { itemType: true },
        });
    }
    async update(id, dto) {
        await this.findOne(id);
        if (dto.code) {
            const conflict = await this.prisma.pricingHeader.findFirst({
                where: { code: dto.code, NOT: { id } },
            });
            if (conflict)
                throw new common_1.ConflictException(`Code "${dto.code}" already exists`);
        }
        return this.prisma.pricingHeader.update({
            where: { id },
            data: {
                ...dto,
                ...(dto.effectiveDate ? { effectiveDate: new Date(dto.effectiveDate) } : {}),
            },
            include: { itemType: true },
        });
    }
    async remove(id) {
        await this.findOne(id);
        return this.prisma.pricingHeader.delete({ where: { id } });
    }
};
exports.PricingHeaderService = PricingHeaderService;
exports.PricingHeaderService = PricingHeaderService = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [prisma_service_1.PrismaService])
], PricingHeaderService);
//# sourceMappingURL=pricing-header.service.js.map