"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.RouteService = void 0;
const api_locale_1 = require("@hed-hog/api-locale");
const api_pagination_1 = require("@hed-hog/api-pagination");
const api_prisma_1 = require("@hed-hog/api-prisma");
const common_1 = require("@nestjs/common");
let RouteService = class RouteService {
    constructor(prismaService, paginationService) {
        this.prismaService = prismaService;
        this.paginationService = paginationService;
    }
    async list(paginationParams) {
        const fields = ['url', 'method', 'tool_name', 'name'];
        const OR = this.prismaService.createInsensitiveSearch(fields, paginationParams);
        return this.paginationService.paginate(this.prismaService.route, paginationParams, {
            where: {
                OR,
            },
        });
    }
    async get(routeId, locale) {
        const route = await this.prismaService.route.findUnique({ where: { id: routeId } });
        if (!route) {
            throw new common_1.NotFoundException((0, api_locale_1.getLocaleText)('itemNotFound', locale, `Route with ID ${routeId} not found`).replace('{{item}}', 'Route'));
        }
        return route;
    }
    async create({ url, method, type = 'HTTP', tool_name, name }, locale) {
        if (type === 'HTTP' && url && method) {
            const existingRoute = await this.prismaService.route.findFirst({
                where: { url, method },
            });
            if (existingRoute) {
                throw new common_1.BadRequestException((0, api_locale_1.getLocaleText)('itemAlreadyExists', locale, `Route with URL ${url} and method ${method} already exists`).replace('{{item}}', 'Route'));
            }
        }
        if (type === 'MCP' && tool_name) {
            const existingTool = await this.prismaService.route.findFirst({
                where: { tool_name },
            });
            if (existingTool) {
                throw new common_1.BadRequestException((0, api_locale_1.getLocaleText)('itemAlreadyExists', locale, `MCP tool '${tool_name}' already exists`).replace('{{item}}', 'MCP tool'));
            }
        }
        return this.prismaService.route.create({ data: { url, method, type: type, tool_name, name } });
    }
    async update({ id, data }, locale) {
        const routeExists = await this.prismaService.route.findUnique({
            where: { id },
        });
        if (!routeExists) {
            throw new common_1.NotFoundException((0, api_locale_1.getLocaleText)('itemNotFound', locale, `Route with ID ${id} not found`).replace('{{item}}', 'Route'));
        }
        return this.prismaService.route.update({
            where: { id },
            data,
        });
    }
    async delete({ ids }, locale) {
        const existingRoutes = await this.prismaService.route.findMany({
            where: {
                id: {
                    in: ids,
                },
            },
        });
        if (existingRoutes.length !== ids.length) {
            const existingIds = existingRoutes.map((route) => route.id);
            const missingIds = ids.filter((id) => !existingIds.includes(id));
            throw new common_1.NotFoundException((0, api_locale_1.getLocaleText)('itemsNotFound', locale, `Routes with IDs ${missingIds.join(', ')} not found`).replace('{{items}}', 'Routes'));
        }
        return this.prismaService.route.deleteMany({
            where: {
                id: {
                    in: ids,
                },
            },
        });
    }
    async listRoles(locale, routeId, paginationParams) {
        return this.paginationService.paginate(this.prismaService.role, paginationParams, {
            include: {
                role_locale: {
                    where: {
                        locale: {
                            code: locale,
                        },
                    },
                    select: {
                        name: true,
                        description: true,
                    },
                },
                role_route: {
                    where: {
                        route_id: routeId,
                    },
                    select: {
                        route_id: true,
                        role_id: true,
                    },
                },
            },
        }, 'role_locale');
    }
    async updateRoles(routeId, data) {
        await this.prismaService.role_route.deleteMany({
            where: {
                route_id: routeId,
            },
        });
        return this.prismaService.role_route.createMany({
            data: data.ids.map((roleId) => ({
                role_id: roleId,
                route_id: routeId,
            })),
            skipDuplicates: true,
        });
    }
    async listScreens(locale, routeId, paginationParams) {
        return this.paginationService.paginate(this.prismaService.screen, paginationParams, {
            include: {
                screen_locale: {
                    where: {
                        locale: {
                            code: locale,
                        },
                    },
                    select: {
                        name: true,
                    },
                },
                route_screen: {
                    where: {
                        route_id: routeId,
                    },
                    select: {
                        route_id: true,
                        screen_id: true,
                    },
                },
            },
        }, 'screen_locale');
    }
    async updateScreens(routeId, data) {
        await this.prismaService.route_screen.deleteMany({
            where: {
                route_id: routeId,
            },
        });
        return this.prismaService.route_screen.createMany({
            data: data.ids.map((screenId) => ({
                screen_id: screenId,
                route_id: routeId,
            })),
            skipDuplicates: true,
        });
    }
};
exports.RouteService = RouteService;
exports.RouteService = RouteService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, common_1.Inject)((0, common_1.forwardRef)(() => api_prisma_1.PrismaService))),
    __param(1, (0, common_1.Inject)((0, common_1.forwardRef)(() => api_pagination_1.PaginationService))),
    __metadata("design:paramtypes", [api_prisma_1.PrismaService,
        api_pagination_1.PaginationService])
], RouteService);
//# sourceMappingURL=route.service.js.map