"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.PluginRepository = void 0;
const common_1 = require("@nestjs/common");
const kysely_1 = require("kysely");
const postgres_1 = require("kysely/helpers/postgres");
const nestjs_kysely_1 = require("nestjs-kysely");
const promises_1 = require("node:fs/promises");
const database_1 = require("../database");
const decorators_1 = require("../decorators");
let PluginRepository = class PluginRepository {
    db;
    constructor(db) {
        this.db = db;
    }
    async loadPlugin(manifest, basePath) {
        return this.db.transaction().execute(async (tx) => {
            const plugin = await tx
                .insertInto('plugin')
                .values({
                name: manifest.name,
                title: manifest.title,
                description: manifest.description,
                author: manifest.author,
                version: manifest.version,
                wasmPath: `${basePath}/${manifest.wasm.path}`,
            })
                .onConflict((oc) => oc.column('name').doUpdateSet({
                title: manifest.title,
                description: manifest.description,
                author: manifest.author,
                version: manifest.version,
                wasmPath: `${basePath}/${manifest.wasm.path}`,
            }))
                .returningAll()
                .executeTakeFirstOrThrow();
            const filters = manifest.filters
                ? await tx
                    .insertInto('plugin_filter')
                    .values(manifest.filters.map((filter) => ({
                    pluginId: plugin.id,
                    methodName: filter.methodName,
                    title: filter.title,
                    description: filter.description,
                    supportedContexts: filter.supportedContexts,
                    schema: filter.schema,
                })))
                    .onConflict((oc) => oc.column('methodName').doUpdateSet((eb) => ({
                    pluginId: eb.ref('excluded.pluginId'),
                    title: eb.ref('excluded.title'),
                    description: eb.ref('excluded.description'),
                    supportedContexts: eb.ref('excluded.supportedContexts'),
                    schema: eb.ref('excluded.schema'),
                })))
                    .returningAll()
                    .execute()
                : [];
            const actions = manifest.actions
                ? await tx
                    .insertInto('plugin_action')
                    .values(manifest.actions.map((action) => ({
                    pluginId: plugin.id,
                    methodName: action.methodName,
                    title: action.title,
                    description: action.description,
                    supportedContexts: action.supportedContexts,
                    schema: action.schema,
                })))
                    .onConflict((oc) => oc.column('methodName').doUpdateSet((eb) => ({
                    pluginId: eb.ref('excluded.pluginId'),
                    title: eb.ref('excluded.title'),
                    description: eb.ref('excluded.description'),
                    supportedContexts: eb.ref('excluded.supportedContexts'),
                    schema: eb.ref('excluded.schema'),
                })))
                    .returningAll()
                    .execute()
                : [];
            return { plugin, filters, actions };
        });
    }
    async readDirectory(path) {
        return (0, promises_1.readdir)(path, { withFileTypes: true });
    }
    getPlugin(id) {
        return this.db
            .selectFrom('plugin')
            .select((eb) => [
            ...database_1.columns.plugin,
            (0, postgres_1.jsonArrayFrom)(eb.selectFrom('plugin_filter').selectAll().whereRef('plugin_filter.pluginId', '=', 'plugin.id')).as('filters'),
            (0, postgres_1.jsonArrayFrom)(eb.selectFrom('plugin_action').selectAll().whereRef('plugin_action.pluginId', '=', 'plugin.id')).as('actions'),
        ])
            .where('plugin.id', '=', id)
            .executeTakeFirst();
    }
    getPluginByName(name) {
        return this.db
            .selectFrom('plugin')
            .select((eb) => [
            ...database_1.columns.plugin,
            (0, postgres_1.jsonArrayFrom)(eb.selectFrom('plugin_filter').selectAll().whereRef('plugin_filter.pluginId', '=', 'plugin.id')).as('filters'),
            (0, postgres_1.jsonArrayFrom)(eb.selectFrom('plugin_action').selectAll().whereRef('plugin_action.pluginId', '=', 'plugin.id')).as('actions'),
        ])
            .where('plugin.name', '=', name)
            .executeTakeFirst();
    }
    getAllPlugins() {
        return this.db
            .selectFrom('plugin')
            .select((eb) => [
            ...database_1.columns.plugin,
            (0, postgres_1.jsonArrayFrom)(eb.selectFrom('plugin_filter').selectAll().whereRef('plugin_filter.pluginId', '=', 'plugin.id')).as('filters'),
            (0, postgres_1.jsonArrayFrom)(eb.selectFrom('plugin_action').selectAll().whereRef('plugin_action.pluginId', '=', 'plugin.id')).as('actions'),
        ])
            .orderBy('plugin.name')
            .execute();
    }
    getFilter(id) {
        return this.db.selectFrom('plugin_filter').selectAll().where('id', '=', id).executeTakeFirst();
    }
    getFiltersByPlugin(pluginId) {
        return this.db.selectFrom('plugin_filter').selectAll().where('pluginId', '=', pluginId).execute();
    }
    getAction(id) {
        return this.db.selectFrom('plugin_action').selectAll().where('id', '=', id).executeTakeFirst();
    }
    getActionsByPlugin(pluginId) {
        return this.db.selectFrom('plugin_action').selectAll().where('pluginId', '=', pluginId).execute();
    }
};
exports.PluginRepository = PluginRepository;
__decorate([
    (0, decorators_1.GenerateSql)({ params: [decorators_1.DummyValue.UUID] }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", void 0)
], PluginRepository.prototype, "getPlugin", null);
__decorate([
    (0, decorators_1.GenerateSql)({ params: [decorators_1.DummyValue.STRING] }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", void 0)
], PluginRepository.prototype, "getPluginByName", null);
__decorate([
    (0, decorators_1.GenerateSql)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", void 0)
], PluginRepository.prototype, "getAllPlugins", null);
__decorate([
    (0, decorators_1.GenerateSql)({ params: [decorators_1.DummyValue.UUID] }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", void 0)
], PluginRepository.prototype, "getFilter", null);
__decorate([
    (0, decorators_1.GenerateSql)({ params: [decorators_1.DummyValue.UUID] }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", void 0)
], PluginRepository.prototype, "getFiltersByPlugin", null);
__decorate([
    (0, decorators_1.GenerateSql)({ params: [decorators_1.DummyValue.UUID] }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", void 0)
], PluginRepository.prototype, "getAction", null);
__decorate([
    (0, decorators_1.GenerateSql)({ params: [decorators_1.DummyValue.UUID] }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", void 0)
], PluginRepository.prototype, "getActionsByPlugin", null);
exports.PluginRepository = PluginRepository = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, nestjs_kysely_1.InjectKysely)()),
    __metadata("design:paramtypes", [kysely_1.Kysely])
], PluginRepository);
//# sourceMappingURL=plugin.repository.js.map