"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assertActiveGuardForEstate = assertActiveGuardForEstate;
const common_1 = require("@nestjs/common");
const client_1 = require("@prisma/client");
const profile_completion_1 = require("./profile-completion");
async function assertActiveGuardForEstate(prisma, guardId, estateId, user, deviceId) {
    const guard = await prisma.guard.findFirst({
        where: {
            id: guardId,
            estateId,
            status: client_1.AccountStatus.ACTIVE
        }
    });
    if (!guard) {
        throw new common_1.NotFoundException('Active guard was not found in this estate');
    }
    if (user.role === client_1.UserRole.GUARD && guard.userId !== user.id) {
        throw new common_1.ForbiddenException('Guard identity does not match the authenticated user');
    }
    const completion = (0, profile_completion_1.calculateProfileCompletion)(client_1.UserRole.GUARD, guard);
    if (!completion.complete) {
        throw new common_1.ForbiddenException({
            message: 'Guard profile must be complete before scanning visitors',
            profileCompletion: completion.completion,
            missing: completion.missing
        });
    }
    if (!guard.assignedGateId) {
        throw new common_1.ForbiddenException('Guard must be assigned to a gate before scanning visitors');
    }
    const normalizedDeviceId = deviceId?.trim();
    if (!normalizedDeviceId) {
        return guard;
    }
    if (guard.deviceId && guard.deviceId !== normalizedDeviceId) {
        throw new common_1.ForbiddenException('Guard account is assigned to a different device');
    }
    if (!guard.deviceId) {
        try {
            return await prisma.guard.update({
                where: { id: guard.id },
                data: { deviceId: normalizedDeviceId }
            });
        }
        catch (error) {
            if (error instanceof client_1.Prisma.PrismaClientKnownRequestError && error.code === 'P2002') {
                throw new common_1.ConflictException('This device is already assigned to another guard');
            }
            throw error;
        }
    }
    return guard;
}
//# sourceMappingURL=guard-access.js.map