"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.RequestsService = 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 prisma_service_1 = require("../database/prisma.service");
const residentRequestCategories = [
    { label: 'Security Risk', category: 'SECURITY', metadataKey: 'SECURITY_RISK' },
    { label: 'Street Light Issue', category: 'INFRASTRUCTURE', metadataKey: 'STREET_LIGHT_ISSUE' },
    { label: 'Environment Issue', category: 'ESTATE_SERVICES', metadataKey: 'ENVIRONMENT_ISSUE' },
    { label: 'Debris/Waste', category: 'ESTATE_SERVICES', metadataKey: 'DEBRIS_WASTE' },
    { label: 'Noise Complaint', category: 'ESTATE_SERVICES', metadataKey: 'NOISE_COMPLAINT' },
    { label: 'Maintenance', category: 'INFRASTRUCTURE', metadataKey: 'MAINTENANCE' },
    { label: 'Water Issue', category: 'INFRASTRUCTURE', metadataKey: 'WATER_ISSUE' },
    { label: 'Power/Electricity Issue', category: 'INFRASTRUCTURE', metadataKey: 'POWER_ELECTRICITY_ISSUE' },
    { label: 'Security Support', category: 'SECURITY', metadataKey: 'SECURITY_SUPPORT' },
    { label: 'Infrastructure', category: 'INFRASTRUCTURE', metadataKey: 'INFRASTRUCTURE' },
    { label: 'Other', category: 'SUPPORT', metadataKey: 'OTHER' }
];
const residentRequestPriorities = [
    { label: 'Low', value: 'LOW' },
    { label: 'Normal', value: 'NORMAL' },
    { label: 'High', value: 'HIGH' },
    { label: 'Urgent', value: 'URGENT' }
];
let RequestsService = class RequestsService {
    prisma;
    audit;
    constructor(prisma, audit) {
        this.prisma = prisma;
        this.audit = audit;
    }
    async findAll(user, estateId, residentId, status) {
        const scopedEstateId = (0, estate_scope_1.resolveEstateScope)(user, estateId);
        const resident = user.role === client_1.UserRole.RESIDENT ? await this.getResidentForUser(user.id, scopedEstateId) : null;
        return this.prisma.residentRequest.findMany({
            where: {
                estateId: scopedEstateId,
                residentId: resident ? resident.id : residentId,
                status
            },
            include: {
                resident: true,
                messages: { orderBy: { createdAt: 'asc' }, include: { author: { select: { id: true, name: true, role: true } } } }
            },
            orderBy: { createdAt: 'desc' },
            take: 100
        });
    }
    getOptions() {
        return {
            categories: residentRequestCategories,
            priorities: residentRequestPriorities,
            fields: ['title', 'category', 'priority', 'description', 'photoUrl', 'location'],
            photoUploadOptional: true
        };
    }
    async create(dto, user) {
        const estateId = (0, estate_scope_1.resolveEstateScope)(user, dto.estateId);
        const resident = user.role === client_1.UserRole.RESIDENT
            ? await this.getResidentForUser(user.id, estateId)
            : await this.prisma.resident.findFirst({ where: { id: dto.residentId, estateId } });
        if (!resident) {
            throw new common_1.NotFoundException('Resident not found');
        }
        const request = await this.prisma.residentRequest.create({
            data: {
                requestCode: `REQ-${(0, code_generator_1.generateCode)(8)}`,
                estateId,
                residentId: resident.id,
                category: dto.category,
                priority: dto.priority,
                title: dto.title.trim(),
                description: dto.description.trim(),
                metadata: this.toJson({
                    ...(dto.metadata ?? {}),
                    categoryLabel: dto.metadata?.categoryLabel ?? this.categoryLabel(dto.category),
                    location: dto.metadata?.location ?? null,
                    photoUrl: dto.metadata?.photoUrl ?? null
                })
            },
            include: { resident: true }
        });
        await this.notifyEstateSecurity(estateId, request.id, request.title);
        await this.audit.record({
            estateId,
            actorType: 'USER',
            actorId: user.id,
            action: 'RESIDENT_REQUEST_CREATED',
            metadata: { requestId: request.id, category: request.category, priority: request.priority }
        });
        return request;
    }
    async respond(id, dto, user) {
        const existing = await this.prisma.residentRequest.findUnique({
            where: { id },
            include: { resident: true }
        });
        if (!existing) {
            throw new common_1.NotFoundException('Request not found');
        }
        (0, estate_scope_1.resolveEstateScope)(user, existing.estateId);
        if (user.role === client_1.UserRole.RESIDENT) {
            throw new common_1.ForbiddenException('Residents cannot respond to requests as security');
        }
        const updated = await this.prisma.$transaction(async (tx) => {
            const request = await tx.residentRequest.update({
                where: { id },
                data: {
                    status: dto.status,
                    assignedToId: dto.assignedToId,
                    resolvedAt: dto.status === client_1.ResidentRequestStatus.RESOLVED ? new Date() : undefined,
                    closedAt: dto.status === client_1.ResidentRequestStatus.CLOSED ? new Date() : undefined
                },
                include: { resident: true }
            });
            await tx.residentRequestMessage.create({
                data: {
                    requestId: id,
                    authorId: user.id,
                    message: dto.message.trim(),
                    metadata: this.toJson(dto.metadata)
                }
            });
            await tx.appNotification.create({
                data: {
                    estateId: request.estateId,
                    userId: request.resident.userId,
                    channel: client_1.NotificationChannel.IN_APP,
                    status: client_1.NotificationStatus.PENDING,
                    title: `Request update: ${request.title}`,
                    body: dto.message.trim(),
                    data: { requestId: request.id, status: request.status, deepLink: '/requests' }
                }
            });
            return request;
        });
        await this.audit.record({
            estateId: existing.estateId,
            actorType: 'USER',
            actorId: user.id,
            action: 'RESIDENT_REQUEST_RESPONDED',
            metadata: { requestId: id, status: dto.status }
        });
        return updated;
    }
    async notifyEstateSecurity(estateId, requestId, title) {
        const recipients = await this.prisma.user.findMany({
            where: {
                estateId,
                status: 'ACTIVE',
                role: { in: [client_1.UserRole.ESTATE_ADMIN, client_1.UserRole.SECURITY_SUPERVISOR, client_1.UserRole.GUARD] }
            },
            select: { id: true }
        });
        await this.prisma.appNotification.createMany({
            data: recipients.map((recipient) => ({
                estateId,
                userId: recipient.id,
                channel: client_1.NotificationChannel.IN_APP,
                status: client_1.NotificationStatus.PENDING,
                title: 'New resident request',
                body: title,
                data: { requestId, deepLink: '/requests' }
            }))
        });
    }
    categoryLabel(category) {
        return residentRequestCategories.find((item) => item.category === category)?.label ?? category;
    }
    async getResidentForUser(userId, estateId) {
        return this.prisma.resident.findFirst({ where: { userId, estateId } });
    }
    toJson(value) {
        if (value === undefined) {
            return undefined;
        }
        return JSON.parse(JSON.stringify(value));
    }
};
exports.RequestsService = RequestsService;
exports.RequestsService = RequestsService = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [prisma_service_1.PrismaService,
        audit_service_1.AuditService])
], RequestsService);
//# sourceMappingURL=requests.service.js.map