"use strict";
/**
 * PrototipoService - Gestión de prototipos de vivienda
 *
 * CRUD de prototipos con soporte multi-tenant.
 *
 * @module Construction
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.PrototipoService = void 0;
const typeorm_1 = require("typeorm");
class PrototipoService {
    repository;
    constructor(repository) {
        this.repository = repository;
    }
    /**
     * Listar prototipos
     */
    async findAll(options) {
        const { tenantId, page = 1, limit = 20, search, type, isActive } = options;
        const query = this.repository
            .createQueryBuilder('p')
            .where('p.tenant_id = :tenantId', { tenantId })
            .andWhere('p.deleted_at IS NULL');
        if (search) {
            query.andWhere('(p.code ILIKE :search OR p.name ILIKE :search)', { search: `%${search}%` });
        }
        if (type) {
            query.andWhere('p.type = :type', { type });
        }
        if (isActive !== undefined) {
            query.andWhere('p.is_active = :isActive', { isActive });
        }
        const total = await query.getCount();
        const items = await query
            .skip((page - 1) * limit)
            .take(limit)
            .orderBy('p.name', 'ASC')
            .getMany();
        return { items, total };
    }
    /**
     * Obtener prototipo por ID
     */
    async findById(id, tenantId) {
        return this.repository.findOne({
            where: { id, tenantId, deletedAt: (0, typeorm_1.IsNull)() },
        });
    }
    /**
     * Obtener prototipo por código
     */
    async findByCode(code, tenantId) {
        return this.repository.findOne({
            where: { code, tenantId, deletedAt: (0, typeorm_1.IsNull)() },
        });
    }
    /**
     * Crear prototipo
     */
    async create(tenantId, dto, createdBy) {
        const existing = await this.findByCode(dto.code, tenantId);
        if (existing) {
            throw new Error('Prototype code already exists');
        }
        return this.repository.save(this.repository.create({
            tenantId,
            ...dto,
            createdBy,
            isActive: true,
        }));
    }
    /**
     * Actualizar prototipo
     */
    async update(id, tenantId, dto, updatedBy) {
        const prototipo = await this.findById(id, tenantId);
        if (!prototipo) {
            throw new Error('Prototype not found');
        }
        // Verificar código único si se está cambiando
        if (dto.code && dto.code !== prototipo.code) {
            const existing = await this.findByCode(dto.code, tenantId);
            if (existing) {
                throw new Error('Prototype code already exists');
            }
        }
        // Exclude metadata from spread to avoid TypeORM type issues
        const { metadata, ...updateData } = dto;
        await this.repository.update(id, {
            ...updateData,
            ...(metadata && { metadata: metadata }),
            updatedBy,
            updatedAt: new Date(),
        });
        return this.findById(id, tenantId);
    }
    /**
     * Eliminar prototipo (soft delete)
     */
    async delete(id, tenantId, _deletedBy) {
        const prototipo = await this.findById(id, tenantId);
        if (!prototipo) {
            throw new Error('Prototype not found');
        }
        // TODO: Verificar si está asignado a lotes antes de eliminar
        await this.repository.update(id, {
            deletedAt: new Date(),
            isActive: false,
        });
    }
    /**
     * Activar/Desactivar prototipo
     */
    async setActive(id, tenantId, isActive) {
        const prototipo = await this.findById(id, tenantId);
        if (!prototipo) {
            throw new Error('Prototype not found');
        }
        await this.repository.update(id, { isActive });
        return this.findById(id, tenantId);
    }
}
exports.PrototipoService = PrototipoService;
//# sourceMappingURL=prototipo.service.js.map