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 { Arg, Ctx, ObjectType, Query, Resolver, Field, Int } from 'type-graphql';
import { RunQuery } from '@memberjunction/core';
import { RequireSystemUser } from '../directives/RequireSystemUser.js';
import { GraphQLJSONObject } from 'graphql-type-json';
import { GetReadOnlyProvider } from '../util.js';
let RunQueryResultType = class RunQueryResultType {
    QueryID;
    QueryName;
    Success;
    Results;
    RowCount;
    TotalRowCount;
    ExecutionTime;
    ErrorMessage;
    AppliedParameters;
    CacheHit;
    CacheTTLRemaining;
};
__decorate([
    Field(),
    __metadata("design:type", String)
], RunQueryResultType.prototype, "QueryID", void 0);
__decorate([
    Field(),
    __metadata("design:type", String)
], RunQueryResultType.prototype, "QueryName", void 0);
__decorate([
    Field(),
    __metadata("design:type", Boolean)
], RunQueryResultType.prototype, "Success", void 0);
__decorate([
    Field(),
    __metadata("design:type", String)
], RunQueryResultType.prototype, "Results", void 0);
__decorate([
    Field(),
    __metadata("design:type", Number)
], RunQueryResultType.prototype, "RowCount", void 0);
__decorate([
    Field(),
    __metadata("design:type", Number)
], RunQueryResultType.prototype, "TotalRowCount", void 0);
__decorate([
    Field(),
    __metadata("design:type", Number)
], RunQueryResultType.prototype, "ExecutionTime", void 0);
__decorate([
    Field(),
    __metadata("design:type", String)
], RunQueryResultType.prototype, "ErrorMessage", void 0);
__decorate([
    Field(() => String, { nullable: true }),
    __metadata("design:type", String)
], RunQueryResultType.prototype, "AppliedParameters", void 0);
__decorate([
    Field(() => Boolean, { nullable: true }),
    __metadata("design:type", Boolean)
], RunQueryResultType.prototype, "CacheHit", void 0);
__decorate([
    Field(() => Int, { nullable: true }),
    __metadata("design:type", Number)
], RunQueryResultType.prototype, "CacheTTLRemaining", void 0);
RunQueryResultType = __decorate([
    ObjectType()
], RunQueryResultType);
export { RunQueryResultType };
let RunQueryResolver = class RunQueryResolver {
    async findQuery(md, QueryID, QueryName, CategoryID, CategoryPath, refreshMetadataIfNotFound = false) {
        const queries = md.Queries.filter(q => {
            if (QueryID) {
                return q.ID.trim().toLowerCase() === QueryID.trim().toLowerCase();
            }
            else if (QueryName) {
                let matches = q.Name.trim().toLowerCase() === QueryName.trim().toLowerCase();
                if (CategoryID) {
                    matches = matches && q.CategoryID?.trim().toLowerCase() === CategoryID.trim().toLowerCase();
                }
                if (CategoryPath) {
                    matches = matches && q.Category?.trim().toLowerCase() === CategoryPath.trim().toLowerCase();
                }
                return matches;
            }
            return false;
        });
        if (queries.length === 0) {
            if (refreshMetadataIfNotFound) {
                await md.Refresh();
                return this.findQuery(md, QueryID, QueryName, CategoryID, CategoryPath, false);
            }
            else {
                return null;
            }
        }
        else {
            return queries[0];
        }
    }
    async GetQueryData(QueryID, context, CategoryID, CategoryPath, Parameters, MaxRows, StartRow, ForceAuditLog, AuditLogDescription) {
        const provider = GetReadOnlyProvider(context.providers, { allowFallbackToReadWrite: true });
        const md = provider;
        const rq = new RunQuery(provider);
        console.log('GetQueryData called with:', { QueryID, Parameters, MaxRows, StartRow, ForceAuditLog, AuditLogDescription });
        const result = await rq.RunQuery({
            QueryID: QueryID,
            CategoryID: CategoryID,
            CategoryPath: CategoryPath,
            Parameters: Parameters,
            MaxRows: MaxRows,
            StartRow: StartRow,
            ForceAuditLog: ForceAuditLog,
            AuditLogDescription: AuditLogDescription
        }, context.userPayload.userRecord);
        console.log('RunQuery result:', {
            Success: result.Success,
            ErrorMessage: result.ErrorMessage,
            AppliedParameters: result.AppliedParameters
        });
        let queryName = result.QueryName;
        if (!queryName) {
            try {
                const queryInfo = await this.findQuery(md, QueryID, undefined, CategoryID, CategoryPath, true);
                if (queryInfo) {
                    queryName = queryInfo.Name;
                }
            }
            catch (error) {
                console.error('Error finding query to get name:', error);
            }
        }
        return {
            QueryID: QueryID,
            QueryName: queryName || 'Unknown Query',
            Success: result.Success ?? false,
            Results: JSON.stringify(result.Results ?? null),
            RowCount: result.RowCount ?? 0,
            TotalRowCount: result.TotalRowCount ?? 0,
            ExecutionTime: result.ExecutionTime ?? 0,
            ErrorMessage: result.ErrorMessage || '',
            AppliedParameters: result.AppliedParameters ? JSON.stringify(result.AppliedParameters) : undefined,
            CacheHit: result.CacheHit,
            CacheTTLRemaining: result.CacheTTLRemaining
        };
    }
    async GetQueryDataByName(QueryName, context, CategoryID, CategoryPath, Parameters, MaxRows, StartRow, ForceAuditLog, AuditLogDescription) {
        const provider = GetReadOnlyProvider(context.providers, { allowFallbackToReadWrite: true });
        const rq = new RunQuery(provider);
        const result = await rq.RunQuery({
            QueryName: QueryName,
            CategoryID: CategoryID,
            CategoryPath: CategoryPath,
            Parameters: Parameters,
            MaxRows: MaxRows,
            StartRow: StartRow,
            ForceAuditLog: ForceAuditLog,
            AuditLogDescription: AuditLogDescription
        }, context.userPayload.userRecord);
        return {
            QueryID: result.QueryID || '',
            QueryName: QueryName,
            Success: result.Success ?? false,
            Results: JSON.stringify(result.Results ?? null),
            RowCount: result.RowCount ?? 0,
            TotalRowCount: result.TotalRowCount ?? 0,
            ExecutionTime: result.ExecutionTime ?? 0,
            ErrorMessage: result.ErrorMessage || '',
            AppliedParameters: result.AppliedParameters ? JSON.stringify(result.AppliedParameters) : undefined,
            CacheHit: result.CacheHit,
            CacheTTLRemaining: result.CacheTTLRemaining
        };
    }
    async GetQueryDataSystemUser(QueryID, context, CategoryID, CategoryPath, Parameters, MaxRows, StartRow, ForceAuditLog, AuditLogDescription) {
        const provider = GetReadOnlyProvider(context.providers, { allowFallbackToReadWrite: true });
        const md = provider;
        const rq = new RunQuery(provider);
        const result = await rq.RunQuery({
            QueryID: QueryID,
            CategoryID: CategoryID,
            CategoryPath: CategoryPath,
            Parameters: Parameters,
            MaxRows: MaxRows,
            StartRow: StartRow,
            ForceAuditLog: ForceAuditLog,
            AuditLogDescription: AuditLogDescription
        }, context.userPayload.userRecord);
        let queryName = result.QueryName;
        if (!queryName) {
            try {
                const queryInfo = await this.findQuery(md, QueryID, undefined, CategoryID, CategoryPath, true);
                if (queryInfo) {
                    queryName = queryInfo.Name;
                }
            }
            catch (error) {
                console.error('Error finding query to get name:', error);
            }
        }
        return {
            QueryID: QueryID,
            QueryName: queryName || 'Unknown Query',
            Success: result.Success ?? false,
            Results: JSON.stringify(result.Results ?? null),
            RowCount: result.RowCount ?? 0,
            TotalRowCount: result.TotalRowCount ?? 0,
            ExecutionTime: result.ExecutionTime ?? 0,
            ErrorMessage: result.ErrorMessage || '',
            AppliedParameters: result.AppliedParameters ? JSON.stringify(result.AppliedParameters) : undefined,
            CacheHit: result.CacheHit,
            CacheTTLRemaining: result.CacheTTLRemaining
        };
    }
    async GetQueryDataByNameSystemUser(QueryName, context, CategoryID, CategoryPath, Parameters, MaxRows, StartRow, ForceAuditLog, AuditLogDescription) {
        const provider = GetReadOnlyProvider(context.providers, { allowFallbackToReadWrite: true });
        const rq = new RunQuery(provider);
        const result = await rq.RunQuery({
            QueryName: QueryName,
            CategoryID: CategoryID,
            CategoryPath: CategoryPath,
            Parameters: Parameters,
            MaxRows: MaxRows,
            StartRow: StartRow,
            ForceAuditLog: ForceAuditLog,
            AuditLogDescription: AuditLogDescription
        }, context.userPayload.userRecord);
        return {
            QueryID: result.QueryID || '',
            QueryName: QueryName,
            Success: result.Success ?? false,
            Results: JSON.stringify(result.Results ?? null),
            RowCount: result.RowCount ?? 0,
            TotalRowCount: result.TotalRowCount ?? 0,
            ExecutionTime: result.ExecutionTime ?? 0,
            ErrorMessage: result.ErrorMessage || '',
            AppliedParameters: result.AppliedParameters ? JSON.stringify(result.AppliedParameters) : undefined,
            CacheHit: result.CacheHit,
            CacheTTLRemaining: result.CacheTTLRemaining
        };
    }
};
__decorate([
    Query(() => RunQueryResultType),
    __param(0, Arg('QueryID', () => String)),
    __param(1, Ctx()),
    __param(2, Arg('CategoryID', () => String, { nullable: true })),
    __param(3, Arg('CategoryPath', () => String, { nullable: true })),
    __param(4, Arg('Parameters', () => GraphQLJSONObject, { nullable: true })),
    __param(5, Arg('MaxRows', () => Int, { nullable: true })),
    __param(6, Arg('StartRow', () => Int, { nullable: true })),
    __param(7, Arg('ForceAuditLog', () => Boolean, { nullable: true })),
    __param(8, Arg('AuditLogDescription', () => String, { nullable: true })),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object, String, String, Object, Number, Number, Boolean, String]),
    __metadata("design:returntype", Promise)
], RunQueryResolver.prototype, "GetQueryData", null);
__decorate([
    Query(() => RunQueryResultType),
    __param(0, Arg('QueryName', () => String)),
    __param(1, Ctx()),
    __param(2, Arg('CategoryID', () => String, { nullable: true })),
    __param(3, Arg('CategoryPath', () => String, { nullable: true })),
    __param(4, Arg('Parameters', () => GraphQLJSONObject, { nullable: true })),
    __param(5, Arg('MaxRows', () => Int, { nullable: true })),
    __param(6, Arg('StartRow', () => Int, { nullable: true })),
    __param(7, Arg('ForceAuditLog', () => Boolean, { nullable: true })),
    __param(8, Arg('AuditLogDescription', () => String, { nullable: true })),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object, String, String, Object, Number, Number, Boolean, String]),
    __metadata("design:returntype", Promise)
], RunQueryResolver.prototype, "GetQueryDataByName", null);
__decorate([
    RequireSystemUser(),
    Query(() => RunQueryResultType),
    __param(0, Arg('QueryID', () => String)),
    __param(1, Ctx()),
    __param(2, Arg('CategoryID', () => String, { nullable: true })),
    __param(3, Arg('CategoryPath', () => String, { nullable: true })),
    __param(4, Arg('Parameters', () => GraphQLJSONObject, { nullable: true })),
    __param(5, Arg('MaxRows', () => Int, { nullable: true })),
    __param(6, Arg('StartRow', () => Int, { nullable: true })),
    __param(7, Arg('ForceAuditLog', () => Boolean, { nullable: true })),
    __param(8, Arg('AuditLogDescription', () => String, { nullable: true })),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object, String, String, Object, Number, Number, Boolean, String]),
    __metadata("design:returntype", Promise)
], RunQueryResolver.prototype, "GetQueryDataSystemUser", null);
__decorate([
    RequireSystemUser(),
    Query(() => RunQueryResultType),
    __param(0, Arg('QueryName', () => String)),
    __param(1, Ctx()),
    __param(2, Arg('CategoryID', () => String, { nullable: true })),
    __param(3, Arg('CategoryPath', () => String, { nullable: true })),
    __param(4, Arg('Parameters', () => GraphQLJSONObject, { nullable: true })),
    __param(5, Arg('MaxRows', () => Int, { nullable: true })),
    __param(6, Arg('StartRow', () => Int, { nullable: true })),
    __param(7, Arg('ForceAuditLog', () => Boolean, { nullable: true })),
    __param(8, Arg('AuditLogDescription', () => String, { nullable: true })),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object, String, String, Object, Number, Number, Boolean, String]),
    __metadata("design:returntype", Promise)
], RunQueryResolver.prototype, "GetQueryDataByNameSystemUser", null);
RunQueryResolver = __decorate([
    Resolver()
], RunQueryResolver);
export { RunQueryResolver };
//# sourceMappingURL=QueryResolver.js.map