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); }
};
import { Resolver, Mutation, Arg, Ctx, ObjectType, Field } from 'type-graphql';
import { LogError, LogStatus, RunView } from '@memberjunction/core';
import { TemplateEngineServer } from '@memberjunction/templates';
import { ResolverBase } from '../generic/ResolverBase.js';
import { GetReadWriteProvider } from '../util.js';
let TemplateRunResult = class TemplateRunResult {
    success;
    output;
    error;
    executionTimeMs;
};
__decorate([
    Field(),
    __metadata("design:type", Boolean)
], TemplateRunResult.prototype, "success", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], TemplateRunResult.prototype, "output", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", String)
], TemplateRunResult.prototype, "error", void 0);
__decorate([
    Field({ nullable: true }),
    __metadata("design:type", Number)
], TemplateRunResult.prototype, "executionTimeMs", void 0);
TemplateRunResult = __decorate([
    ObjectType()
], TemplateRunResult);
export { TemplateRunResult };
let RunTemplateResolver = class RunTemplateResolver extends ResolverBase {
    async RunTemplate(templateId, { userPayload, providers }, contextData) {
        const startTime = Date.now();
        try {
            LogStatus(`=== RUNNING TEMPLATE FOR ID: ${templateId} ===`);
            let data = {};
            if (contextData) {
                try {
                    data = JSON.parse(contextData);
                }
                catch (parseError) {
                    return {
                        success: false,
                        error: `Invalid JSON in context data: ${parseError.message}`,
                        executionTimeMs: Date.now() - startTime
                    };
                }
            }
            const currentUser = this.GetUserFromPayload(userPayload);
            if (!currentUser) {
                return {
                    success: false,
                    error: 'Unable to determine current user',
                    executionTimeMs: Date.now() - startTime
                };
            }
            const p = GetReadWriteProvider(providers);
            const templateEntity = await p.GetEntityObject('Templates', currentUser);
            await templateEntity.Load(templateId);
            if (!templateEntity.IsSaved) {
                return {
                    success: false,
                    error: `Template with ID ${templateId} not found`,
                    executionTimeMs: Date.now() - startTime
                };
            }
            const rv = new RunView();
            const templateContentResult = await rv.RunView({
                EntityName: 'Template Contents',
                ExtraFilter: `TemplateID = '${templateId}'`,
                OrderBy: 'Priority ASC',
                MaxRows: 1,
                ResultType: 'entity_object'
            }, currentUser);
            if (!templateContentResult.Results || templateContentResult.Results.length === 0) {
                return {
                    success: false,
                    error: `No template content found for template ${templateEntity.Name}`,
                    executionTimeMs: Date.now() - startTime
                };
            }
            await TemplateEngineServer.Instance.Config(true, currentUser);
            const result = await TemplateEngineServer.Instance.RenderTemplate(templateEntity, templateContentResult.Results[0], data, true);
            const executionTime = Date.now() - startTime;
            if (result.Success) {
                LogStatus(`=== TEMPLATE RUN COMPLETED FOR: ${templateEntity.Name} (${executionTime}ms) ===`);
                return {
                    success: true,
                    output: result.Output,
                    executionTimeMs: executionTime
                };
            }
            else {
                LogError(`Template run failed for ${templateEntity.Name}: ${result.Message}`);
                return {
                    success: false,
                    error: result.Message,
                    executionTimeMs: executionTime
                };
            }
        }
        catch (error) {
            const executionTime = Date.now() - startTime;
            LogError(`Template run failed:`, undefined, error);
            return {
                success: false,
                error: error.message || 'Unknown error occurred',
                executionTimeMs: executionTime
            };
        }
    }
};
__decorate([
    Mutation(() => TemplateRunResult),
    __param(0, Arg('templateId')),
    __param(1, Ctx()),
    __param(2, Arg('contextData', { nullable: true })),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object, String]),
    __metadata("design:returntype", Promise)
], RunTemplateResolver.prototype, "RunTemplate", null);
RunTemplateResolver = __decorate([
    Resolver()
], RunTemplateResolver);
export { RunTemplateResolver };
//# sourceMappingURL=RunTemplateResolver.js.map