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, Field, InputType, Int, ObjectType, PubSubEngine, Query, Resolver } from 'type-graphql';
import { ResolverBase } from './ResolverBase.js';
import { LogError } from '@memberjunction/core';
import { RequireSystemUser } from '../directives/RequireSystemUser.js';
import { GetReadOnlyProvider } from '../util.js';
import { KeyValuePairOutputType } from './KeyInputOutputTypes.js';
let RunViewByIDInput = class RunViewByIDInput {
    ViewID;
    ExtraFilter;
    OrderBy;
    Fields;
    UserSearchString;
    ExcludeUserViewRunID;
    OverrideExcludeFilter;
    SaveViewResults;
    ExcludeDataFromAllPriorViewRuns;
    IgnoreMaxRows;
    MaxRows;
    ForceAuditLog;
    AuditLogDescription;
    ResultType;
    StartRow;
};
__decorate([
    Field(() => String),
    __metadata("design:type", String)
], RunViewByIDInput.prototype, "ViewID", void 0);
__decorate([
    Field(() => String, {
        nullable: true,
        description: 'Optional, pass in a valid condition to append to the view WHERE clause. For example, UpdatedAt >= Some Date - if not provided, no filter is applied',
    }),
    __metadata("design:type", String)
], RunViewByIDInput.prototype, "ExtraFilter", void 0);
__decorate([
    Field(() => String, {
        nullable: true,
        description: 'Optional, pass in a valid order by clause sort the results on the server. For example, CreatedAt DESC to order by row creation date in reverse order. Any Valid SQL Order By clause is okay - if not provided, no server-side sorting is applied',
    }),
    __metadata("design:type", String)
], RunViewByIDInput.prototype, "OrderBy", void 0);
__decorate([
    Field(() => [String], {
        nullable: true,
        description: 'Optional, array of entity field names, if not provided, ID and all other columns used in the view columns are returned. If provided, only the fields in the array are returned.',
    }),
    __metadata("design:type", Array)
], RunViewByIDInput.prototype, "Fields", void 0);
__decorate([
    Field(() => String, { nullable: true }),
    __metadata("design:type", String)
], RunViewByIDInput.prototype, "UserSearchString", void 0);
__decorate([
    Field(() => String, { nullable: true, description: 'Pass in a UserViewRun ID value to exclude all records from that run from results' }),
    __metadata("design:type", String)
], RunViewByIDInput.prototype, "ExcludeUserViewRunID", void 0);
__decorate([
    Field(() => String, {
        nullable: true,
        description: 'Pass in a valid condition to append to the view WHERE clause to override the Exclude List. For example, UpdatedAt >= Some Date',
    }),
    __metadata("design:type", String)
], RunViewByIDInput.prototype, "OverrideExcludeFilter", void 0);
__decorate([
    Field(() => Boolean, {
        nullable: true,
        description: 'If set to True, the results of this view are saved into a new UserViewRun record and the UserViewRun.ID is passed back in the results.',
    }),
    __metadata("design:type", Boolean)
], RunViewByIDInput.prototype, "SaveViewResults", void 0);
__decorate([
    Field(() => Boolean, {
        nullable: true,
        description: 'if set to true, the resulting data will filter out ANY records that were ever returned by this view, when the SaveViewResults property was set to true. This is useful if you want to run a particular view over time and make sure the results returned each time are new to the view.',
    }),
    __metadata("design:type", Boolean)
], RunViewByIDInput.prototype, "ExcludeDataFromAllPriorViewRuns", void 0);
__decorate([
    Field(() => Boolean, {
        nullable: true,
        description: 'if set to true, if there IS any UserViewMaxRows property set for the entity in question, it will be IGNORED. This is useful in scenarios where you want to programmatically run a view and get ALL the data back, regardless of the MaxRows setting on the entity.',
    }),
    __metadata("design:type", Boolean)
], RunViewByIDInput.prototype, "IgnoreMaxRows", void 0);
__decorate([
    Field(() => Int, {
        nullable: true,
        description: 'if a value > 0 is provided, and IgnoreMaxRows is set to false, this value is used for the max rows to be returned by the view.',
    }),
    __metadata("design:type", Number)
], RunViewByIDInput.prototype, "MaxRows", void 0);
__decorate([
    Field(() => Boolean, {
        nullable: true,
        description: 'If set to true, an Audit Log record will be created for the view run, regardless of the property settings in the entity for auditing view runs',
    }),
    __metadata("design:type", Boolean)
], RunViewByIDInput.prototype, "ForceAuditLog", void 0);
__decorate([
    Field(() => String, {
        nullable: true,
        description: "if provided and either ForceAuditLog is set, or the entity's property settings for logging view runs are set to true, this will be used as the Audit Log Description.",
    }),
    __metadata("design:type", String)
], RunViewByIDInput.prototype, "AuditLogDescription", void 0);
__decorate([
    Field(() => String, {
        nullable: true,
        description: 'Optional, pass in entity_object, simple, or count_only as options to specify the type of result you want back. Defaults to simple if not provided',
    }),
    __metadata("design:type", String)
], RunViewByIDInput.prototype, "ResultType", void 0);
__decorate([
    Field(() => Int, {
        nullable: true,
        description: 'If a value > 0 is provided, this value will be used to offset the rows returned.',
    }),
    __metadata("design:type", Number)
], RunViewByIDInput.prototype, "StartRow", void 0);
RunViewByIDInput = __decorate([
    InputType()
], RunViewByIDInput);
export { RunViewByIDInput };
let RunViewByNameInput = class RunViewByNameInput {
    ViewName;
    ExtraFilter;
    OrderBy;
    Fields;
    UserSearchString;
    ExcludeUserViewRunID;
    OverrideExcludeFilter;
    SaveViewResults;
    ExcludeDataFromAllPriorViewRuns;
    IgnoreMaxRows;
    MaxRows;
    ForceAuditLog;
    AuditLogDescription;
    ResultType;
    StartRow;
};
__decorate([
    Field(() => String),
    __metadata("design:type", String)
], RunViewByNameInput.prototype, "ViewName", void 0);
__decorate([
    Field(() => String, {
        nullable: true,
        description: 'Optional, pass in a valid condition to append to the view WHERE clause. For example, UpdatedAt >= Some Date - if not provided, no filter is applied',
    }),
    __metadata("design:type", String)
], RunViewByNameInput.prototype, "ExtraFilter", void 0);
__decorate([
    Field(() => String, {
        nullable: true,
        description: 'Optional, pass in a valid order by clause sort the results on the server. For example, CreatedAt DESC to order by row creation date in reverse order. Any Valid SQL Order By clause is okay - if not provided, no server-side sorting is applied',
    }),
    __metadata("design:type", String)
], RunViewByNameInput.prototype, "OrderBy", void 0);
__decorate([
    Field(() => [String], {
        nullable: true,
        description: 'Optional, array of entity field names, if not provided, ID and all other columns used in the view are returned. If provided, only the fields in the array are returned.',
    }),
    __metadata("design:type", Array)
], RunViewByNameInput.prototype, "Fields", void 0);
__decorate([
    Field(() => String, { nullable: true }),
    __metadata("design:type", String)
], RunViewByNameInput.prototype, "UserSearchString", void 0);
__decorate([
    Field(() => String, { nullable: true, description: 'Pass in a UserViewRun ID value to exclude all records from that run from results' }),
    __metadata("design:type", String)
], RunViewByNameInput.prototype, "ExcludeUserViewRunID", void 0);
__decorate([
    Field(() => String, {
        nullable: true,
        description: 'Pass in a valid condition to append to the view WHERE clause to override the Exclude List. For example, UpdatedAt >= Some Date',
    }),
    __metadata("design:type", String)
], RunViewByNameInput.prototype, "OverrideExcludeFilter", void 0);
__decorate([
    Field(() => Boolean, {
        nullable: true,
        description: 'If set to True, the results of this view are saved into a new UserViewRun record and the UserViewRun.ID is passed back in the results.',
    }),
    __metadata("design:type", Boolean)
], RunViewByNameInput.prototype, "SaveViewResults", void 0);
__decorate([
    Field(() => Boolean, {
        nullable: true,
        description: 'if set to true, the resulting data will filter out ANY records that were ever returned by this view, when the SaveViewResults property was set to true. This is useful if you want to run a particular view over time and make sure the results returned each time are new to the view.',
    }),
    __metadata("design:type", Boolean)
], RunViewByNameInput.prototype, "ExcludeDataFromAllPriorViewRuns", void 0);
__decorate([
    Field(() => Boolean, {
        nullable: true,
        description: 'if set to true, if there IS any UserViewMaxRows property set for the entity in question, it will be IGNORED. This is useful in scenarios where you want to programmatically run a view and get ALL the data back, regardless of the MaxRows setting on the entity.',
    }),
    __metadata("design:type", Boolean)
], RunViewByNameInput.prototype, "IgnoreMaxRows", void 0);
__decorate([
    Field(() => Int, {
        nullable: true,
        description: 'if a value > 0 is provided, and IgnoreMaxRows is set to false, this value is used for the max rows to be returned by the view.',
    }),
    __metadata("design:type", Number)
], RunViewByNameInput.prototype, "MaxRows", void 0);
__decorate([
    Field(() => Boolean, {
        nullable: true,
        description: 'If set to true, an Audit Log record will be created for the view run, regardless of the property settings in the entity for auditing view runs',
    }),
    __metadata("design:type", Boolean)
], RunViewByNameInput.prototype, "ForceAuditLog", void 0);
__decorate([
    Field(() => String, {
        nullable: true,
        description: "if provided and either ForceAuditLog is set, or the entity's property settings for logging view runs are set to true, this will be used as the Audit Log Description.",
    }),
    __metadata("design:type", String)
], RunViewByNameInput.prototype, "AuditLogDescription", void 0);
__decorate([
    Field(() => String, {
        nullable: true,
        description: 'Optional, pass in entity_object, simple, or count_only as options to specify the type of result you want back. Defaults to simple if not provided',
    }),
    __metadata("design:type", String)
], RunViewByNameInput.prototype, "ResultType", void 0);
__decorate([
    Field(() => Int, {
        nullable: true,
        description: 'If a value > 0 is provided, this value will be used to offset the rows returned.',
    }),
    __metadata("design:type", Number)
], RunViewByNameInput.prototype, "StartRow", void 0);
RunViewByNameInput = __decorate([
    InputType()
], RunViewByNameInput);
export { RunViewByNameInput };
let RunDynamicViewInput = class RunDynamicViewInput {
    EntityName;
    ExtraFilter;
    OrderBy;
    Fields;
    UserSearchString;
    ExcludeUserViewRunID;
    OverrideExcludeFilter;
    IgnoreMaxRows;
    MaxRows;
    ForceAuditLog;
    AuditLogDescription;
    ResultType;
    StartRow;
};
__decorate([
    Field(() => String),
    __metadata("design:type", String)
], RunDynamicViewInput.prototype, "EntityName", void 0);
__decorate([
    Field(() => String, {
        nullable: true,
        description: 'Optional, pass in a valid condition to use as the view WHERE clause. For example, UpdatedAt >= Some Date - if not provided, no filter is applied',
    }),
    __metadata("design:type", String)
], RunDynamicViewInput.prototype, "ExtraFilter", void 0);
__decorate([
    Field(() => String, {
        nullable: true,
        description: 'Optional, pass in a valid order by clause sort the results on the server. For example, CreatedAt DESC to order by row creation date in reverse order. Any Valid SQL Order By clause is okay - if not provided, no server-side sorting is applied',
    }),
    __metadata("design:type", String)
], RunDynamicViewInput.prototype, "OrderBy", void 0);
__decorate([
    Field(() => [String], {
        nullable: true,
        description: 'Optional, array of entity field names, if not provided, all columns are returned. If provided, only the fields in the array are returned.',
    }),
    __metadata("design:type", Array)
], RunDynamicViewInput.prototype, "Fields", void 0);
__decorate([
    Field(() => String, { nullable: true }),
    __metadata("design:type", String)
], RunDynamicViewInput.prototype, "UserSearchString", void 0);
__decorate([
    Field(() => String, { nullable: true, description: 'Pass in a UserViewRun ID value to exclude all records from that run from results' }),
    __metadata("design:type", String)
], RunDynamicViewInput.prototype, "ExcludeUserViewRunID", void 0);
__decorate([
    Field(() => String, {
        nullable: true,
        description: 'Pass in a valid condition to append to the view WHERE clause to override the Exclude List. For example, UpdatedAt >= Some Date',
    }),
    __metadata("design:type", String)
], RunDynamicViewInput.prototype, "OverrideExcludeFilter", void 0);
__decorate([
    Field(() => Boolean, {
        nullable: true,
        description: 'if set to true, if there IS any UserViewMaxRows property set for the entity in question, it will be IGNORED. This is useful in scenarios where you want to programmatically run a view and get ALL the data back, regardless of the MaxRows setting on the entity.',
    }),
    __metadata("design:type", Boolean)
], RunDynamicViewInput.prototype, "IgnoreMaxRows", void 0);
__decorate([
    Field(() => Int, {
        nullable: true,
        description: 'if a value > 0 is provided, and IgnoreMaxRows is set to false, this value is used for the max rows to be returned by the view.',
    }),
    __metadata("design:type", Number)
], RunDynamicViewInput.prototype, "MaxRows", void 0);
__decorate([
    Field(() => Boolean, {
        nullable: true,
        description: 'If set to true, an Audit Log record will be created for the view run, regardless of the property settings in the entity for auditing view runs',
    }),
    __metadata("design:type", Boolean)
], RunDynamicViewInput.prototype, "ForceAuditLog", void 0);
__decorate([
    Field(() => String, {
        nullable: true,
        description: "if provided and either ForceAuditLog is set, or the entity's property settings for logging view runs are set to true, this will be used as the Audit Log Description.",
    }),
    __metadata("design:type", String)
], RunDynamicViewInput.prototype, "AuditLogDescription", void 0);
__decorate([
    Field(() => String, {
        nullable: true,
        description: 'Optional, pass in entity_object, simple, or count_only as options to specify the type of result you want back. Defaults to simple if not provided',
    }),
    __metadata("design:type", String)
], RunDynamicViewInput.prototype, "ResultType", void 0);
__decorate([
    Field(() => Int, {
        nullable: true,
        description: 'If a value > 0 is provided, this value will be used to offset the rows returned.',
    }),
    __metadata("design:type", Number)
], RunDynamicViewInput.prototype, "StartRow", void 0);
RunDynamicViewInput = __decorate([
    InputType()
], RunDynamicViewInput);
export { RunDynamicViewInput };
let RunViewGenericInput = class RunViewGenericInput {
    EntityName;
    ExtraFilter;
    OrderBy;
    Fields;
    UserSearchString;
    ExcludeUserViewRunID;
    OverrideExcludeFilter;
    SaveViewResults;
    ExcludeDataFromAllPriorViewRuns;
    IgnoreMaxRows;
    MaxRows;
    ForceAuditLog;
    AuditLogDescription;
    ResultType;
    StartRow;
};
__decorate([
    Field(() => String),
    __metadata("design:type", String)
], RunViewGenericInput.prototype, "EntityName", void 0);
__decorate([
    Field(() => String, {
        nullable: true,
        description: 'Optional, pass in a valid condition to use as the view WHERE clause. For example, UpdatedAt >= Some Date - if not provided, no filter is applied',
    }),
    __metadata("design:type", String)
], RunViewGenericInput.prototype, "ExtraFilter", void 0);
__decorate([
    Field(() => String, {
        nullable: true,
        description: 'Optional, pass in a valid order by clause sort the results on the server. For example, CreatedAt DESC to order by row creation date in reverse order. Any Valid SQL Order By clause is okay - if not provided, no server-side sorting is applied',
    }),
    __metadata("design:type", String)
], RunViewGenericInput.prototype, "OrderBy", void 0);
__decorate([
    Field(() => [String], {
        nullable: true,
        description: 'Optional, array of entity field names, if not provided, all columns are returned. If provided, only the fields in the array are returned.',
    }),
    __metadata("design:type", Array)
], RunViewGenericInput.prototype, "Fields", void 0);
__decorate([
    Field(() => String, { nullable: true }),
    __metadata("design:type", String)
], RunViewGenericInput.prototype, "UserSearchString", void 0);
__decorate([
    Field(() => String, { nullable: true, description: 'Pass in a UserViewRun ID value to exclude all records from that run from results' }),
    __metadata("design:type", String)
], RunViewGenericInput.prototype, "ExcludeUserViewRunID", void 0);
__decorate([
    Field(() => String, {
        nullable: true,
        description: 'Pass in a valid condition to append to the view WHERE clause to override the Exclude List. For example, UpdatedAt >= Some Date',
    }),
    __metadata("design:type", String)
], RunViewGenericInput.prototype, "OverrideExcludeFilter", void 0);
__decorate([
    Field(() => Boolean, {
        nullable: true,
        description: 'If set to True, the results of this view are saved into a new UserViewRun record and the UserViewRun.ID is passed back in the results.',
    }),
    __metadata("design:type", Boolean)
], RunViewGenericInput.prototype, "SaveViewResults", void 0);
__decorate([
    Field(() => Boolean, {
        nullable: true,
        description: 'if set to true, the resulting data will filter out ANY records that were ever returned by this view, when the SaveViewResults property was set to true. This is useful if you want to run a particular view over time and make sure the results returned each time are new to the view.',
    }),
    __metadata("design:type", Boolean)
], RunViewGenericInput.prototype, "ExcludeDataFromAllPriorViewRuns", void 0);
__decorate([
    Field(() => Boolean, {
        nullable: true,
        description: 'if set to true, if there IS any UserViewMaxRows property set for the entity in question, it will be IGNORED. This is useful in scenarios where you want to programmatically run a view and get ALL the data back, regardless of the MaxRows setting on the entity.',
    }),
    __metadata("design:type", Boolean)
], RunViewGenericInput.prototype, "IgnoreMaxRows", void 0);
__decorate([
    Field(() => Int, {
        nullable: true,
        description: 'if a value > 0 is provided, and IgnoreMaxRows is set to false, this value is used for the max rows to be returned by the view.',
    }),
    __metadata("design:type", Number)
], RunViewGenericInput.prototype, "MaxRows", void 0);
__decorate([
    Field(() => Boolean, {
        nullable: true,
        description: 'If set to true, an Audit Log record will be created for the view run, regardless of the property settings in the entity for auditing view runs',
    }),
    __metadata("design:type", Boolean)
], RunViewGenericInput.prototype, "ForceAuditLog", void 0);
__decorate([
    Field(() => String, {
        nullable: true,
        description: "if provided and either ForceAuditLog is set, or the entity's property settings for logging view runs are set to true, this will be used as the Audit Log Description.",
    }),
    __metadata("design:type", String)
], RunViewGenericInput.prototype, "AuditLogDescription", void 0);
__decorate([
    Field(() => String, {
        nullable: true,
        description: 'Optional, pass in entity_object, simple, or count_only as options to specify the type of result you want back. Defaults to simple if not provided',
    }),
    __metadata("design:type", String)
], RunViewGenericInput.prototype, "ResultType", void 0);
__decorate([
    Field(() => Int, {
        nullable: true,
        description: 'If a value > 0 is provided, this value will be used to offset the rows returned.',
    }),
    __metadata("design:type", Number)
], RunViewGenericInput.prototype, "StartRow", void 0);
RunViewGenericInput = __decorate([
    InputType()
], RunViewGenericInput);
export { RunViewGenericInput };
let RunViewCacheStatusInput = class RunViewCacheStatusInput {
    maxUpdatedAt;
    rowCount;
};
__decorate([
    Field(() => String, { description: 'The maximum __mj_UpdatedAt value from cached results' }),
    __metadata("design:type", String)
], RunViewCacheStatusInput.prototype, "maxUpdatedAt", void 0);
__decorate([
    Field(() => Int, { description: 'The number of rows in cached results' }),
    __metadata("design:type", Number)
], RunViewCacheStatusInput.prototype, "rowCount", void 0);
RunViewCacheStatusInput = __decorate([
    InputType()
], RunViewCacheStatusInput);
export { RunViewCacheStatusInput };
let RunViewWithCacheCheckInput = class RunViewWithCacheCheckInput {
    params;
    cacheStatus;
};
__decorate([
    Field(() => RunDynamicViewInput, { description: 'The RunView parameters' }),
    __metadata("design:type", RunDynamicViewInput)
], RunViewWithCacheCheckInput.prototype, "params", void 0);
__decorate([
    Field(() => RunViewCacheStatusInput, {
        nullable: true,
        description: 'Optional cache status - if provided, server will check if cache is current'
    }),
    __metadata("design:type", RunViewCacheStatusInput)
], RunViewWithCacheCheckInput.prototype, "cacheStatus", void 0);
RunViewWithCacheCheckInput = __decorate([
    InputType()
], RunViewWithCacheCheckInput);
export { RunViewWithCacheCheckInput };
let RunViewWithCacheCheckResultOutput = class RunViewWithCacheCheckResultOutput {
    viewIndex;
    status;
    Results;
    maxUpdatedAt;
    rowCount;
    errorMessage;
};
__decorate([
    Field(() => Int, { description: 'The index of this view in the batch request' }),
    __metadata("design:type", Number)
], RunViewWithCacheCheckResultOutput.prototype, "viewIndex", void 0);
__decorate([
    Field(() => String, { description: "'current', 'stale', or 'error'" }),
    __metadata("design:type", String)
], RunViewWithCacheCheckResultOutput.prototype, "status", void 0);
__decorate([
    Field(() => [RunViewGenericResultRow], {
        nullable: true,
        description: 'Fresh results - only populated when status is stale'
    }),
    __metadata("design:type", Array)
], RunViewWithCacheCheckResultOutput.prototype, "Results", void 0);
__decorate([
    Field(() => String, { nullable: true, description: 'Max __mj_UpdatedAt from results when stale' }),
    __metadata("design:type", String)
], RunViewWithCacheCheckResultOutput.prototype, "maxUpdatedAt", void 0);
__decorate([
    Field(() => Int, { nullable: true, description: 'Row count of results when stale' }),
    __metadata("design:type", Number)
], RunViewWithCacheCheckResultOutput.prototype, "rowCount", void 0);
__decorate([
    Field(() => String, { nullable: true, description: 'Error message if status is error' }),
    __metadata("design:type", String)
], RunViewWithCacheCheckResultOutput.prototype, "errorMessage", void 0);
RunViewWithCacheCheckResultOutput = __decorate([
    ObjectType()
], RunViewWithCacheCheckResultOutput);
export { RunViewWithCacheCheckResultOutput };
let RunViewsWithCacheCheckOutput = class RunViewsWithCacheCheckOutput {
    success;
    results;
    errorMessage;
};
__decorate([
    Field(() => Boolean, { description: 'Whether the overall operation succeeded' }),
    __metadata("design:type", Boolean)
], RunViewsWithCacheCheckOutput.prototype, "success", void 0);
__decorate([
    Field(() => [RunViewWithCacheCheckResultOutput], { description: 'Results for each view in the batch' }),
    __metadata("design:type", Array)
], RunViewsWithCacheCheckOutput.prototype, "results", void 0);
__decorate([
    Field(() => String, { nullable: true, description: 'Overall error message if success is false' }),
    __metadata("design:type", String)
], RunViewsWithCacheCheckOutput.prototype, "errorMessage", void 0);
RunViewsWithCacheCheckOutput = __decorate([
    ObjectType()
], RunViewsWithCacheCheckOutput);
export { RunViewsWithCacheCheckOutput };
let RunViewResultRow = class RunViewResultRow {
    PrimaryKey;
    EntityID;
    Data;
};
__decorate([
    Field(() => [KeyValuePairOutputType], {
        description: 'Primary key values for the record'
    }),
    __metadata("design:type", Array)
], RunViewResultRow.prototype, "PrimaryKey", void 0);
__decorate([
    Field(() => String),
    __metadata("design:type", String)
], RunViewResultRow.prototype, "EntityID", void 0);
__decorate([
    Field(() => String),
    __metadata("design:type", String)
], RunViewResultRow.prototype, "Data", void 0);
RunViewResultRow = __decorate([
    ObjectType()
], RunViewResultRow);
export { RunViewResultRow };
let RunViewGenericResultRow = class RunViewGenericResultRow {
    PrimaryKey;
    EntityID;
    Data;
};
__decorate([
    Field(() => [KeyValuePairOutputType], {
        description: 'Primary key values for the record'
    }),
    __metadata("design:type", Array)
], RunViewGenericResultRow.prototype, "PrimaryKey", void 0);
__decorate([
    Field(() => String),
    __metadata("design:type", String)
], RunViewGenericResultRow.prototype, "EntityID", void 0);
__decorate([
    Field(() => String),
    __metadata("design:type", String)
], RunViewGenericResultRow.prototype, "Data", void 0);
RunViewGenericResultRow = __decorate([
    ObjectType()
], RunViewGenericResultRow);
export { RunViewGenericResultRow };
let RunViewResult = class RunViewResult {
    Results;
    UserViewRunID;
    RowCount;
    TotalRowCount;
    ExecutionTime;
    ErrorMessage;
    Success;
};
__decorate([
    Field(() => [RunViewResultRow]),
    __metadata("design:type", Array)
], RunViewResult.prototype, "Results", void 0);
__decorate([
    Field(() => String, { nullable: true }),
    __metadata("design:type", String)
], RunViewResult.prototype, "UserViewRunID", void 0);
__decorate([
    Field(() => Int, { nullable: true }),
    __metadata("design:type", Number)
], RunViewResult.prototype, "RowCount", void 0);
__decorate([
    Field(() => Int, { nullable: true }),
    __metadata("design:type", Number)
], RunViewResult.prototype, "TotalRowCount", void 0);
__decorate([
    Field(() => Int, { nullable: true }),
    __metadata("design:type", Number)
], RunViewResult.prototype, "ExecutionTime", void 0);
__decorate([
    Field(() => String, { nullable: true }),
    __metadata("design:type", String)
], RunViewResult.prototype, "ErrorMessage", void 0);
__decorate([
    Field(() => Boolean, { nullable: false }),
    __metadata("design:type", Boolean)
], RunViewResult.prototype, "Success", void 0);
RunViewResult = __decorate([
    ObjectType()
], RunViewResult);
export { RunViewResult };
let RunViewGenericResult = class RunViewGenericResult {
    Results;
    UserViewRunID;
    RowCount;
    TotalRowCount;
    ExecutionTime;
    ErrorMessage;
    Success;
};
__decorate([
    Field(() => [RunViewGenericResultRow]),
    __metadata("design:type", Array)
], RunViewGenericResult.prototype, "Results", void 0);
__decorate([
    Field(() => String, { nullable: true }),
    __metadata("design:type", String)
], RunViewGenericResult.prototype, "UserViewRunID", void 0);
__decorate([
    Field(() => Int, { nullable: true }),
    __metadata("design:type", Number)
], RunViewGenericResult.prototype, "RowCount", void 0);
__decorate([
    Field(() => Int, { nullable: true }),
    __metadata("design:type", Number)
], RunViewGenericResult.prototype, "TotalRowCount", void 0);
__decorate([
    Field(() => Int, { nullable: true }),
    __metadata("design:type", Number)
], RunViewGenericResult.prototype, "ExecutionTime", void 0);
__decorate([
    Field(() => String, { nullable: true }),
    __metadata("design:type", String)
], RunViewGenericResult.prototype, "ErrorMessage", void 0);
__decorate([
    Field(() => Boolean, { nullable: false }),
    __metadata("design:type", Boolean)
], RunViewGenericResult.prototype, "Success", void 0);
RunViewGenericResult = __decorate([
    ObjectType()
], RunViewGenericResult);
export { RunViewGenericResult };
let RunViewResolver = class RunViewResolver extends ResolverBase {
    async RunViewByName(input, { providers, userPayload }, pubSub) {
        try {
            const provider = GetReadOnlyProvider(providers, { allowFallbackToReadWrite: true });
            const rawData = await super.RunViewByNameGeneric(input, provider, userPayload, pubSub);
            if (rawData === null)
                return null;
            const viewInfo = super.safeFirstArrayElement(await super.findBy(provider, "User Views", { Name: input.ViewName }, userPayload.userRecord));
            const entity = provider.Entities.find((e) => e.ID === viewInfo.EntityID);
            const returnData = this.processRawData(rawData.Results, viewInfo.EntityID, entity);
            return {
                Results: returnData,
                UserViewRunID: rawData?.UserViewRunID,
                RowCount: rawData?.RowCount,
                TotalRowCount: rawData?.TotalRowCount,
                ExecutionTime: rawData?.ExecutionTime,
            };
        }
        catch (err) {
            console.log(err);
            return null;
        }
    }
    async RunViewByID(input, { providers, userPayload }, pubSub) {
        try {
            const provider = GetReadOnlyProvider(providers, { allowFallbackToReadWrite: true });
            const rawData = await super.RunViewByIDGeneric(input, provider, userPayload, pubSub);
            if (rawData === null)
                return null;
            const viewInfo = super.safeFirstArrayElement(await super.findBy(provider, "User Views", { ID: input.ViewID }, userPayload.userRecord));
            const entity = provider.Entities.find((e) => e.ID === viewInfo.EntityID);
            const returnData = this.processRawData(rawData.Results, viewInfo.EntityID, entity);
            return {
                Results: returnData,
                UserViewRunID: rawData?.UserViewRunID,
                RowCount: rawData?.RowCount,
                TotalRowCount: rawData?.TotalRowCount,
                ExecutionTime: rawData?.ExecutionTime,
            };
        }
        catch (err) {
            console.log(err);
            return null;
        }
    }
    async RunDynamicView(input, { providers, userPayload }, pubSub) {
        try {
            const provider = GetReadOnlyProvider(providers, { allowFallbackToReadWrite: true });
            const rawData = await super.RunDynamicViewGeneric(input, provider, userPayload, pubSub);
            if (rawData === null)
                return null;
            const entity = provider.Entities.find((e) => e.Name === input.EntityName);
            const returnData = this.processRawData(rawData.Results, entity.ID, entity);
            return {
                Results: returnData,
                UserViewRunID: rawData?.UserViewRunID,
                RowCount: rawData?.RowCount,
                TotalRowCount: rawData?.TotalRowCount,
                ExecutionTime: rawData?.ExecutionTime,
            };
        }
        catch (err) {
            console.log(err);
            return null;
        }
    }
    async RunViews(input, { providers, userPayload }, pubSub) {
        try {
            const provider = GetReadOnlyProvider(providers, { allowFallbackToReadWrite: true });
            const rawData = await super.RunViewsGeneric(input, provider, userPayload);
            if (!rawData) {
                return null;
            }
            let results = [];
            for (const [index, data] of rawData.entries()) {
                const entity = provider.Entities.find((e) => e.Name === input[index].EntityName);
                const returnData = this.processRawData(data.Results, entity.ID, entity);
                results.push({
                    Results: returnData,
                    UserViewRunID: data?.UserViewRunID,
                    RowCount: data?.RowCount,
                    TotalRowCount: data?.TotalRowCount,
                    ExecutionTime: data?.ExecutionTime,
                    Success: data?.Success,
                });
            }
            return results;
        }
        catch (err) {
            LogError(err);
            return null;
        }
    }
    async RunViewByNameSystemUser(input, { providers, userPayload }, pubSub) {
        try {
            const provider = GetReadOnlyProvider(providers, { allowFallbackToReadWrite: true });
            const rawData = await super.RunViewByNameGeneric(input, provider, userPayload, pubSub);
            if (rawData === null) {
                return {
                    Results: [],
                    Success: false,
                    ErrorMessage: `Failed to execute view: ${input.ViewName}`,
                    RowCount: 0,
                    TotalRowCount: 0,
                    ExecutionTime: 0
                };
            }
            const entity = provider.Entities.find((e) => e.Name === input.ViewName);
            const entityId = entity ? entity.ID : null;
            const returnData = this.processRawData(rawData.Results, entityId, entity);
            return {
                Results: returnData,
                UserViewRunID: rawData?.UserViewRunID,
                RowCount: rawData?.RowCount,
                TotalRowCount: rawData?.TotalRowCount,
                ExecutionTime: rawData?.ExecutionTime,
                Success: rawData?.Success,
                ErrorMessage: rawData?.ErrorMessage,
            };
        }
        catch (err) {
            const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
            LogError(err);
            return {
                Results: [],
                Success: false,
                ErrorMessage: errorMessage,
                RowCount: 0,
                TotalRowCount: 0,
                ExecutionTime: 0
            };
        }
    }
    async RunViewByIDSystemUser(input, { providers, userPayload }, pubSub) {
        try {
            const provider = GetReadOnlyProvider(providers, { allowFallbackToReadWrite: true });
            const rawData = await super.RunViewByIDGeneric(input, provider, userPayload, pubSub);
            if (rawData === null) {
                return {
                    Results: [],
                    Success: false,
                    ErrorMessage: `Failed to execute view with ID: ${input.ViewID}`,
                    RowCount: 0,
                    TotalRowCount: 0,
                    ExecutionTime: 0
                };
            }
            const viewInfo = super.safeFirstArrayElement(await super.findBy(provider, "User Views", { ID: input.ViewID }, userPayload.userRecord));
            const entity = provider.Entities.find((e) => e.ID === viewInfo.EntityID);
            const returnData = this.processRawData(rawData.Results, viewInfo.EntityID, entity);
            return {
                Results: returnData,
                UserViewRunID: rawData?.UserViewRunID,
                RowCount: rawData?.RowCount,
                TotalRowCount: rawData?.TotalRowCount,
                ExecutionTime: rawData?.ExecutionTime,
                Success: rawData?.Success,
                ErrorMessage: rawData?.ErrorMessage,
            };
        }
        catch (err) {
            const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
            LogError(err);
            return {
                Results: [],
                Success: false,
                ErrorMessage: errorMessage,
                RowCount: 0,
                TotalRowCount: 0,
                ExecutionTime: 0
            };
        }
    }
    async RunDynamicViewSystemUser(input, { providers, userPayload }, pubSub) {
        try {
            const provider = GetReadOnlyProvider(providers, { allowFallbackToReadWrite: true });
            const rawData = await super.RunDynamicViewGeneric(input, provider, userPayload, pubSub);
            if (rawData === null) {
                return {
                    Results: [],
                    Success: false,
                    ErrorMessage: 'Failed to execute dynamic view',
                    RowCount: 0,
                    TotalRowCount: 0,
                    ExecutionTime: 0
                };
            }
            const entity = provider.Entities.find((e) => e.Name === input.EntityName);
            if (!entity) {
                const errorMsg = `Entity ${input.EntityName} not found in metadata`;
                LogError(new Error(errorMsg));
                return {
                    Results: [],
                    Success: false,
                    ErrorMessage: errorMsg,
                    RowCount: 0,
                    TotalRowCount: 0,
                    ExecutionTime: 0
                };
            }
            const returnData = this.processRawData(rawData.Results, entity.ID, entity);
            return {
                Results: returnData,
                UserViewRunID: rawData?.UserViewRunID,
                RowCount: rawData?.RowCount,
                TotalRowCount: rawData?.TotalRowCount,
                ExecutionTime: rawData?.ExecutionTime,
                Success: rawData?.Success,
                ErrorMessage: rawData?.ErrorMessage,
            };
        }
        catch (err) {
            const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
            LogError(err);
            return {
                Results: [],
                Success: false,
                ErrorMessage: errorMessage,
                RowCount: 0,
                TotalRowCount: 0,
                ExecutionTime: 0
            };
        }
    }
    async RunViewsSystemUser(input, { providers, userPayload }, pubSub) {
        try {
            const provider = GetReadOnlyProvider(providers, { allowFallbackToReadWrite: true });
            const rawData = await super.RunViewsGeneric(input, provider, userPayload);
            if (!rawData) {
                return null;
            }
            let results = [];
            for (const [index, data] of rawData.entries()) {
                const entity = provider.Entities.find((e) => e.Name === input[index].EntityName);
                if (!entity) {
                    LogError(new Error(`Entity with name ${input[index].EntityName} not found`));
                    continue;
                }
                const returnData = this.processRawData(data.Results, entity.ID, entity);
                results.push({
                    Results: returnData,
                    UserViewRunID: data?.UserViewRunID,
                    RowCount: data?.RowCount,
                    TotalRowCount: data?.TotalRowCount,
                    ExecutionTime: data?.ExecutionTime,
                    Success: data?.Success,
                    ErrorMessage: data?.ErrorMessage,
                });
            }
            return results;
        }
        catch (err) {
            LogError(err);
            return null;
        }
    }
    async RunViewsWithCacheCheck(input, { providers, userPayload }) {
        try {
            const provider = GetReadOnlyProvider(providers, { allowFallbackToReadWrite: true });
            const sqlProvider = provider;
            if (!sqlProvider.RunViewsWithCacheCheck) {
                throw new Error('Provider does not support RunViewsWithCacheCheck');
            }
            const coreParams = input.map(item => ({
                params: {
                    EntityName: item.params.EntityName,
                    ExtraFilter: item.params.ExtraFilter,
                    OrderBy: item.params.OrderBy,
                    Fields: item.params.Fields,
                    UserSearchString: item.params.UserSearchString,
                    ExcludeUserViewRunID: item.params.ExcludeUserViewRunID,
                    OverrideExcludeFilter: item.params.OverrideExcludeFilter,
                    IgnoreMaxRows: item.params.IgnoreMaxRows,
                    MaxRows: item.params.MaxRows,
                    ForceAuditLog: item.params.ForceAuditLog,
                    AuditLogDescription: item.params.AuditLogDescription,
                    ResultType: (item.params.ResultType || 'simple'),
                    StartRow: item.params.StartRow,
                },
                cacheStatus: item.cacheStatus ? {
                    maxUpdatedAt: item.cacheStatus.maxUpdatedAt,
                    rowCount: item.cacheStatus.rowCount,
                } : undefined,
            }));
            const response = await sqlProvider.RunViewsWithCacheCheck(coreParams, userPayload.userRecord);
            const transformedResults = response.results.map((result, index) => {
                const inputItem = input[index];
                const entity = provider.Entities.find(e => e.Name === inputItem.params.EntityName);
                if (result.status === 'stale' && result.results && entity) {
                    const processedRows = this.processRawData(result.results, entity.ID, entity);
                    return {
                        viewIndex: result.viewIndex,
                        status: result.status,
                        Results: processedRows,
                        maxUpdatedAt: result.maxUpdatedAt,
                        rowCount: result.rowCount,
                        errorMessage: result.errorMessage,
                    };
                }
                return {
                    viewIndex: result.viewIndex,
                    status: result.status,
                    Results: undefined,
                    maxUpdatedAt: result.maxUpdatedAt,
                    rowCount: result.rowCount,
                    errorMessage: result.errorMessage,
                };
            });
            return {
                success: response.success,
                results: transformedResults,
                errorMessage: response.errorMessage,
            };
        }
        catch (err) {
            const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
            LogError(err);
            return {
                success: false,
                results: [],
                errorMessage,
            };
        }
    }
    processRawData(rawData, entityId, entityInfo) {
        const returnResult = [];
        for (let i = 0; i < rawData.length; i++) {
            const row = rawData[i];
            const primaryKey = entityInfo.PrimaryKeys.map(pk => ({
                FieldName: pk.Name,
                Value: row[pk.Name]?.toString() || ''
            }));
            returnResult.push({
                PrimaryKey: primaryKey,
                EntityID: entityId,
                Data: JSON.stringify(row),
            });
        }
        return returnResult;
    }
};
__decorate([
    Query(() => RunViewResult),
    __param(0, Arg('input', () => RunViewByNameInput)),
    __param(1, Ctx()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [RunViewByNameInput, Object, PubSubEngine]),
    __metadata("design:returntype", Promise)
], RunViewResolver.prototype, "RunViewByName", null);
__decorate([
    Query(() => RunViewResult),
    __param(0, Arg('input', () => RunViewByIDInput)),
    __param(1, Ctx()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [RunViewByIDInput, Object, PubSubEngine]),
    __metadata("design:returntype", Promise)
], RunViewResolver.prototype, "RunViewByID", null);
__decorate([
    Query(() => RunViewResult),
    __param(0, Arg('input', () => RunDynamicViewInput)),
    __param(1, Ctx()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [RunDynamicViewInput, Object, PubSubEngine]),
    __metadata("design:returntype", Promise)
], RunViewResolver.prototype, "RunDynamicView", null);
__decorate([
    Query(() => [RunViewGenericResult]),
    __param(0, Arg('input', () => [RunViewGenericInput])),
    __param(1, Ctx()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Array, Object, PubSubEngine]),
    __metadata("design:returntype", Promise)
], RunViewResolver.prototype, "RunViews", null);
__decorate([
    RequireSystemUser(),
    Query(() => RunViewResult),
    __param(0, Arg('input', () => RunViewByNameInput)),
    __param(1, Ctx()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [RunViewByNameInput, Object, PubSubEngine]),
    __metadata("design:returntype", Promise)
], RunViewResolver.prototype, "RunViewByNameSystemUser", null);
__decorate([
    RequireSystemUser(),
    Query(() => RunViewResult),
    __param(0, Arg('input', () => RunViewByIDInput)),
    __param(1, Ctx()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [RunViewByIDInput, Object, PubSubEngine]),
    __metadata("design:returntype", Promise)
], RunViewResolver.prototype, "RunViewByIDSystemUser", null);
__decorate([
    RequireSystemUser(),
    Query(() => RunViewResult),
    __param(0, Arg('input', () => RunDynamicViewInput)),
    __param(1, Ctx()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [RunDynamicViewInput, Object, PubSubEngine]),
    __metadata("design:returntype", Promise)
], RunViewResolver.prototype, "RunDynamicViewSystemUser", null);
__decorate([
    RequireSystemUser(),
    Query(() => [RunViewGenericResult]),
    __param(0, Arg('input', () => [RunViewGenericInput])),
    __param(1, Ctx()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Array, Object, PubSubEngine]),
    __metadata("design:returntype", Promise)
], RunViewResolver.prototype, "RunViewsSystemUser", null);
__decorate([
    Query(() => RunViewsWithCacheCheckOutput),
    __param(0, Arg('input', () => [RunViewWithCacheCheckInput])),
    __param(1, Ctx()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Array, Object]),
    __metadata("design:returntype", Promise)
], RunViewResolver.prototype, "RunViewsWithCacheCheck", null);
RunViewResolver = __decorate([
    Resolver(RunViewResultRow)
], RunViewResolver);
export { RunViewResolver };
//# sourceMappingURL=RunViewResolver.js.map