"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.EstatesService = void 0;
const common_1 = require("@nestjs/common");
const client_1 = require("@prisma/client");
const audit_service_1 = require("../audit/audit.service");
const prisma_service_1 = require("../database/prisma.service");
let EstatesService = class EstatesService {
    prisma;
    audit;
    constructor(prisma, audit) {
        this.prisma = prisma;
        this.audit = audit;
    }
    findAll(user) {
        if (user.role === client_1.UserRole.SUPER_ADMIN) {
            return this.prisma.estate.findMany({ orderBy: { createdAt: 'desc' } });
        }
        if (user.role === client_1.UserRole.SALES_ADMIN) {
            return this.prisma.estate.findMany({
                where: { salesPartnerId: user.id },
                orderBy: { createdAt: 'desc' },
                include: { users: { where: { role: client_1.UserRole.ESTATE_ADMIN }, take: 3 } }
            });
        }
        if (!user.estateId) {
            throw new common_1.ForbiddenException('Estate-scoped user is missing an estate');
        }
        return this.prisma.estate.findMany({ where: { id: user.estateId } });
    }
    async create(dto, user) {
        if (user.role !== client_1.UserRole.SUPER_ADMIN && user.role !== client_1.UserRole.SALES_ADMIN) {
            throw new common_1.ForbiddenException('Only platform admins can onboard estates');
        }
        const estate = await this.createEstateWithOptionalAdmin(dto, user);
        await this.audit.record({
            estateId: estate.id,
            actorType: 'USER',
            actorId: user.id,
            action: 'ESTATE_CREATED',
            metadata: { name: estate.name, salesPartnerId: estate.salesPartnerId ?? null }
        });
        return estate;
    }
    async createEstateWithOptionalAdmin(dto, user) {
        try {
            return await this.prisma.$transaction(async (tx) => {
                const estate = await tx.estate.create({
                    data: {
                        name: dto.name,
                        location: dto.location,
                        unitCount: dto.unitCount ?? 0,
                        estateType: dto.estateType,
                        status: client_1.EstateStatus.ACTIVE,
                        signupStatus: client_1.EstateSignupStatus.APPROVED,
                        subscriptionStatus: client_1.SubscriptionStatus.NONE,
                        activatedAt: new Date(),
                        salesPartnerId: user.role === client_1.UserRole.SALES_ADMIN ? user.id : undefined,
                        settings: {
                            ...(dto.settings ?? {}),
                            onboarding: {
                                adminEmail: dto.adminEmail ?? null
                            }
                        },
                        branding: (dto.branding ?? {})
                    }
                });
                if (user.role === client_1.UserRole.SALES_ADMIN) {
                    await tx.salesPartnerProfile.upsert({
                        where: { salesAdminId: user.id },
                        create: { salesAdminId: user.id, enabled: false, updatedById: user.id },
                        update: {}
                    });
                }
                if (dto.adminName && dto.adminPhone) {
                    await tx.user.create({
                        data: {
                            estateId: estate.id,
                            phone: dto.adminPhone,
                            name: dto.adminName,
                            role: client_1.UserRole.ESTATE_ADMIN,
                            status: client_1.AccountStatus.ACTIVE
                        }
                    });
                }
                return estate;
            });
        }
        catch (error) {
            if (error instanceof client_1.Prisma.PrismaClientKnownRequestError && error.code === 'P2002') {
                throw new common_1.ConflictException('A user with this phone number already exists');
            }
            throw error;
        }
    }
};
exports.EstatesService = EstatesService;
exports.EstatesService = EstatesService = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [prisma_service_1.PrismaService,
        audit_service_1.AuditService])
], EstatesService);
//# sourceMappingURL=estates.service.js.map