"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.CategoriesService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const category_entity_1 = require("./category.entity");
const fs = require("fs");
const path = require("path");
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); }
let CategoriesService = class CategoriesService {
    constructor(repo) {
        this.repo = repo;
    }
    async findAll() {
        const all = await this.repo.find({
            relations: ["parent", "children"],
            order: { name: "ASC" },
        });
        const roots = all.filter(c => !c.parent_id);
        const map = new Map();
        all.forEach(c => { c.children = []; map.set(c.id, c); });
        all.forEach(c => {
            if (c.parent_id) {
                const parent = map.get(c.parent_id);
                if (parent)
                    parent.children.push(c);
            }
        });
        return roots;
    }
    async findOne(id) {
        if (!isUUID(id))
            throw new common_1.NotFoundException("Categoría no encontrada");
        const cat = await this.repo.findOne({ where: { id }, relations: ["parent", "children"] });
        if (!cat)
            throw new common_1.NotFoundException("Categoría no encontrada");
        return cat;
    }
    async create(dto, file) {
        const exists = await this.repo.findOne({ where: { slug: dto.slug } });
        if (exists)
            throw new common_1.ConflictException("El slug ya existe");
        return this.repo.save(this.repo.create({
            name: dto.name,
            slug: dto.slug,
            icon: file ? `/uploads/${file.filename}` : undefined,
            parent_id: dto.parent_id || undefined,
            status: dto.status || "active",
        }));
    }
    async update(id, dto, file) {
        if (!isUUID(id))
            throw new common_1.NotFoundException("Categoría no encontrada");
        const cat = await this.repo.findOne({ where: { id } });
        if (!cat)
            throw new common_1.NotFoundException("Categoría no encontrada");
        if (dto.slug && dto.slug !== cat.slug) {
            const exists = await this.repo.findOne({ where: { slug: dto.slug } });
            if (exists)
                throw new common_1.ConflictException("El slug ya existe");
        }
        const data = { ...cat, ...dto, parent_id: dto.parent_id ?? cat.parent_id };
        if (file) {
            const oldPath = path.join(__dirname, "..", "..", "uploads", cat.icon?.replace("/uploads/", "") || "");
            try {
                if (cat.icon && fs.existsSync(oldPath))
                    fs.unlinkSync(oldPath);
            }
            catch { }
            data.icon = `/uploads/${file.filename}`;
        }
        return this.repo.save(data);
    }
    async remove(id) {
        if (!isUUID(id))
            throw new common_1.NotFoundException("Categoría no encontrada");
        const cat = await this.repo.findOne({ where: { id } });
        if (!cat)
            throw new common_1.NotFoundException("Categoría no encontrada");
        await this.repo.update({ parent_id: id }, { parent_id: null });
        await this.repo.remove(cat);
        return { message: "Categoría eliminada" };
    }
};
exports.CategoriesService = CategoriesService;
exports.CategoriesService = CategoriesService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(category_entity_1.Category)),
    __metadata("design:paramtypes", [typeorm_2.Repository])
], CategoriesService);
//# sourceMappingURL=categories.service.js.map