"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.GatesService = void 0;
const common_1 = require("@nestjs/common");
const client_1 = require("@prisma/client");
const audit_service_1 = require("../audit/audit.service");
const estate_scope_1 = require("../common/estate-scope");
const plan_limits_1 = require("../common/plan-limits");
const prisma_service_1 = require("../database/prisma.service");
let GatesService = class GatesService {
    prisma;
    audit;
    constructor(prisma, audit) {
        this.prisma = prisma;
        this.audit = audit;
    }
    findAll(user, estateId) {
        const scopedEstateId = (0, estate_scope_1.resolveEstateScope)(user, estateId);
        return this.prisma.estateGate.findMany({
            where: { estateId: scopedEstateId },
            include: {
                _count: {
                    select: { guards: true, sessions: true }
                }
            },
            orderBy: [{ isActive: 'desc' }, { name: 'asc' }]
        });
    }
    async create(dto, user) {
        const estateId = (0, estate_scope_1.resolveEstateScope)(user, dto.estateId);
        await this.assertGateLimit(estateId);
        try {
            const gate = await this.prisma.estateGate.create({
                data: {
                    estateId,
                    name: dto.name.trim(),
                    type: dto.type,
                    description: dto.description,
                    metadata: this.toJson(dto.metadata)
                }
            });
            await this.audit.record({
                estateId,
                actorType: 'USER',
                actorId: user.id,
                action: 'ESTATE_GATE_CREATED',
                metadata: { gateId: gate.id, name: gate.name, type: gate.type }
            });
            return gate;
        }
        catch (error) {
            if (error instanceof client_1.Prisma.PrismaClientKnownRequestError && error.code === 'P2002') {
                throw new common_1.ConflictException('A gate with this name already exists in the estate');
            }
            throw error;
        }
    }
    async update(id, dto, user) {
        const existing = await this.prisma.estateGate.findUnique({ where: { id } });
        if (!existing) {
            throw new common_1.NotFoundException('Gate not found');
        }
        (0, estate_scope_1.resolveEstateScope)(user, existing.estateId);
        const gate = await this.prisma.estateGate.update({
            where: { id },
            data: {
                name: dto.name?.trim(),
                type: dto.type,
                description: dto.description,
                isActive: dto.isActive,
                metadata: this.toJson(dto.metadata)
            }
        });
        await this.audit.record({
            estateId: gate.estateId,
            actorType: 'USER',
            actorId: user.id,
            action: 'ESTATE_GATE_UPDATED',
            metadata: { gateId: gate.id, isActive: gate.isActive }
        });
        return gate;
    }
    async assertGateLimit(estateId) {
        const estate = await this.prisma.estate.findUnique({
            where: { id: estateId },
            select: {
                subscriptionPlan: { select: { limits: true, name: true } },
                _count: { select: { gates: true } }
            }
        });
        if (!estate) {
            throw new common_1.NotFoundException('Estate not found');
        }
        const limit = (0, plan_limits_1.getNumericPlanLimit)(estate.subscriptionPlan?.limits, 'gates');
        if (limit !== null && estate._count.gates >= limit) {
            throw new common_1.BadRequestException(`Gate limit reached for ${estate.subscriptionPlan?.name ?? 'this plan'}`);
        }
    }
    toJson(value) {
        if (value === undefined) {
            return undefined;
        }
        return JSON.parse(JSON.stringify(value));
    }
};
exports.GatesService = GatesService;
exports.GatesService = GatesService = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [prisma_service_1.PrismaService,
        audit_service_1.AuditService])
], GatesService);
//# sourceMappingURL=gates.service.js.map