"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.GuardsService = void 0;
const common_1 = require("@nestjs/common");
const client_1 = require("@prisma/client");
const audit_service_1 = require("../audit/audit.service");
const code_generator_1 = require("../common/code-generator");
const estate_scope_1 = require("../common/estate-scope");
const plan_limits_1 = require("../common/plan-limits");
const profile_completion_1 = require("../common/profile-completion");
const prisma_service_1 = require("../database/prisma.service");
let GuardsService = class GuardsService {
    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.guard.findMany({
            where: { estateId: scopedEstateId },
            orderBy: { createdAt: 'desc' }
        });
    }
    async create(dto, user) {
        const estateId = (0, estate_scope_1.resolveEstateScope)(user, dto.estateId);
        await this.assertPlanGuardLimit(estateId);
        const name = this.displayName(dto);
        const generatedGuardCode = `GRD-${(0, code_generator_1.generateCode)()}`;
        const completion = (0, profile_completion_1.calculateProfileCompletion)(client_1.UserRole.GUARD, {
            estateId,
            firstName: dto.firstName,
            lastName: dto.lastName,
            phone: dto.phone,
            guardCode: generatedGuardCode,
            assignedGateId: dto.assignedGateId,
            address: dto.address,
            profileConfirmed: false
        });
        try {
            const guard = await this.prisma.$transaction(async (tx) => {
                const account = await tx.user.create({
                    data: {
                        estateId,
                        name,
                        phone: dto.phone,
                        firstName: dto.firstName,
                        lastName: dto.lastName,
                        address: dto.address,
                        profileCompletion: completion.completion,
                        role: client_1.UserRole.GUARD
                    }
                });
                return tx.guard.create({
                    data: {
                        estateId,
                        userId: account.id,
                        guardCode: generatedGuardCode,
                        name,
                        firstName: dto.firstName,
                        lastName: dto.lastName,
                        phone: dto.phone,
                        address: dto.address,
                        assignedGateId: dto.assignedGateId,
                        profileCompletion: completion.completion,
                        deviceId: dto.deviceId?.trim() || undefined
                    }
                });
            });
            await this.audit.record({
                estateId,
                actorType: 'USER',
                actorId: user.id,
                action: 'GUARD_CREATED',
                metadata: { guardId: guard.id, deviceId: guard.deviceId }
            });
            return guard;
        }
        catch (error) {
            if (error instanceof client_1.Prisma.PrismaClientKnownRequestError && error.code === 'P2002') {
                throw new common_1.ConflictException('A guard with this phone number or device ID already exists');
            }
            throw error;
        }
    }
    displayName(dto) {
        const explicit = dto.name?.trim();
        if (explicit) {
            return explicit;
        }
        const composed = [dto.firstName, dto.lastName].map((value) => value?.trim()).filter(Boolean).join(' ');
        return composed || `Guard ${dto.phone}`;
    }
    async assertPlanGuardLimit(estateId) {
        const estate = await this.prisma.estate.findUnique({
            where: { id: estateId },
            select: {
                subscriptionPlan: { select: { limits: true } },
                _count: { select: { guards: true } }
            }
        });
        const limit = (0, plan_limits_1.getNumericPlanLimit)(estate?.subscriptionPlan?.limits, 'guards');
        if (limit !== null && estate && estate._count.guards >= limit) {
            throw new common_1.ConflictException('Guard limit for this estate plan has been reached');
        }
    }
};
exports.GuardsService = GuardsService;
exports.GuardsService = GuardsService = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [prisma_service_1.PrismaService,
        audit_service_1.AuditService])
], GuardsService);
//# sourceMappingURL=guards.service.js.map