"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);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AdminUsersService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const bcrypt = require("bcrypt");
const crypto = require("crypto");
const user_entity_1 = require("../auth/entities/user.entity");
function isUUID(val) { return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(val); }
const user_profile_entity_1 = require("../auth/entities/user-profile.entity");
const user_verification_entity_1 = require("../auth/entities/user-verification.entity");
let AdminUsersService = class AdminUsersService {
    constructor(userRepo, profileRepo, vfyRepo) {
        this.userRepo = userRepo;
        this.profileRepo = profileRepo;
        this.vfyRepo = vfyRepo;
    }
    async findAll(query) {
        const page = query.page || 1;
        const limit = query.limit || 15;
        const skip = (page - 1) * limit;
        const qb = this.userRepo
            .createQueryBuilder("u")
            .leftJoinAndSelect("u.profile", "p")
            .leftJoinAndSelect("u.role", "r")
            .where("(r.name = :vendedor OR r.name = :comprador)", { vendedor: "vendedor", comprador: "comprador" });
        if (query.search) {
            qb.andWhere("(u.email ILIKE :s OR p.first_name ILIKE :s OR p.last_name ILIKE :s OR p.document_number ILIKE :s)", {
                s: `%${query.search}%`,
            });
        }
        if (query.role) {
            qb.andWhere("r.name = :role", { role: query.role });
        }
        if (query.status) {
            qb.andWhere("u.status = :status", { status: query.status });
        }
        if (query.is_admin === "true") {
            qb.andWhere("r.is_admin = true");
        }
        qb.orderBy("u.created_at", "DESC").skip(skip).take(limit);
        const [data, total] = await qb.getManyAndCount();
        return {
            data: data.map((u) => {
                const { password_hash, ...rest } = u;
                return rest;
            }),
            total,
            page,
            limit,
            totalPages: Math.ceil(total / limit),
        };
    }
    async findOne(id) {
        if (!isUUID(id))
            throw new common_1.NotFoundException("Usuario no encontrado");
        const user = await this.userRepo.findOne({
            where: { id },
            relations: ["profile", "role"],
        });
        if (!user)
            throw new common_1.NotFoundException("Usuario no encontrado");
        const { password_hash, ...result } = user;
        return result;
    }
    async create(dto) {
        const exists = await this.userRepo.findOne({ where: { email: dto.email } });
        if (exists)
            throw new common_1.ConflictException("El correo ya está registrado");
        const hash = await bcrypt.hash(dto.password, 12);
        const referral = crypto.randomBytes(5).toString("hex").toUpperCase();
        const user = await this.userRepo.save(this.userRepo.create({
            email: dto.email, password_hash: hash, phone: dto.phone,
            role_id: dto.role_id, status: dto.status || "active",
            referral_code: referral, is_verified: true,
        }));
        await this.profileRepo.save(this.profileRepo.create({
            user_id: user.id, first_name: dto.first_name, last_name: dto.last_name,
            document_type: dto.document_type, document_number: dto.document_number,
        }));
        return this.findOne(user.id);
    }
    async update(id, dto) {
        if (!isUUID(id))
            throw new common_1.NotFoundException("Usuario no encontrado");
        const user = await this.userRepo.findOne({ where: { id } });
        if (!user)
            throw new common_1.NotFoundException("Usuario no encontrado");
        const userFields = {};
        if (dto.email !== undefined)
            userFields.email = dto.email;
        if (dto.phone !== undefined)
            userFields.phone = dto.phone;
        if (dto.role_id !== undefined)
            userFields.role_id = dto.role_id;
        if (dto.status !== undefined)
            userFields.status = dto.status;
        if (dto.is_verified !== undefined)
            userFields.is_verified = dto.is_verified;
        if (Object.keys(userFields).length > 0) {
            await this.userRepo.update(id, userFields);
        }
        const profileFields = {};
        if (dto.first_name !== undefined)
            profileFields.first_name = dto.first_name;
        if (dto.last_name !== undefined)
            profileFields.last_name = dto.last_name;
        if (dto.document_type !== undefined)
            profileFields.document_type = dto.document_type;
        if (dto.document_number !== undefined)
            profileFields.document_number = dto.document_number;
        if (dto.ruc !== undefined)
            profileFields.ruc = dto.ruc;
        if (dto.razon_social !== undefined)
            profileFields.razon_social = dto.razon_social;
        if (Object.keys(profileFields).length > 0) {
            await this.profileRepo.update({ user_id: id }, profileFields);
        }
        return this.findOne(id);
    }
    async remove(id) {
        if (!isUUID(id))
            throw new common_1.NotFoundException("Usuario no encontrado");
        const user = await this.userRepo.findOne({ where: { id } });
        if (!user)
            throw new common_1.NotFoundException("Usuario no encontrado");
        await this.profileRepo.delete({ user_id: id });
        await this.vfyRepo.delete({ user_id: id });
        await this.userRepo.remove(user);
        return { message: "Usuario eliminado" };
    }
    async getRoles() {
        return this.userRepo.manager.getRepository("Role").find();
    }
};
exports.AdminUsersService = AdminUsersService;
exports.AdminUsersService = AdminUsersService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(user_entity_1.User)),
    __param(1, (0, typeorm_1.InjectRepository)(user_profile_entity_1.UserProfile)),
    __param(2, (0, typeorm_1.InjectRepository)(user_verification_entity_1.UserVerification)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        typeorm_2.Repository,
        typeorm_2.Repository])
], AdminUsersService);
//# sourceMappingURL=admin-users.service.js.map