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 { RunReport } from '@memberjunction/core';
import { Arg, Ctx, Field, Mutation, ObjectType, Query, Resolver } from 'type-graphql';
import { DataContext } from '@memberjunction/data-context';
import { UserCache } from '@memberjunction/sqlserver-dataprovider';
import { z } from 'zod';
import mssql from 'mssql';
import { GetReadOnlyProvider, GetReadWriteProvider } from '../util.js';
let RunReportResultType = class RunReportResultType {
    ReportID;
    Success;
    Results;
    RowCount;
    ExecutionTime;
    ErrorMessage;
};
__decorate([
    Field(),
    __metadata("design:type", String)
], RunReportResultType.prototype, "ReportID", void 0);
__decorate([
    Field(),
    __metadata("design:type", Boolean)
], RunReportResultType.prototype, "Success", void 0);
__decorate([
    Field(),
    __metadata("design:type", String)
], RunReportResultType.prototype, "Results", void 0);
__decorate([
    Field(),
    __metadata("design:type", Number)
], RunReportResultType.prototype, "RowCount", void 0);
__decorate([
    Field(),
    __metadata("design:type", Number)
], RunReportResultType.prototype, "ExecutionTime", void 0);
__decorate([
    Field(),
    __metadata("design:type", String)
], RunReportResultType.prototype, "ErrorMessage", void 0);
RunReportResultType = __decorate([
    ObjectType()
], RunReportResultType);
export { RunReportResultType };
let CreateReportResultType = class CreateReportResultType {
    ReportID;
    ReportName;
    Success;
    ErrorMessage;
};
__decorate([
    Field(),
    __metadata("design:type", String)
], CreateReportResultType.prototype, "ReportID", void 0);
__decorate([
    Field(),
    __metadata("design:type", String)
], CreateReportResultType.prototype, "ReportName", void 0);
__decorate([
    Field(),
    __metadata("design:type", Boolean)
], CreateReportResultType.prototype, "Success", void 0);
__decorate([
    Field(),
    __metadata("design:type", String)
], CreateReportResultType.prototype, "ErrorMessage", void 0);
CreateReportResultType = __decorate([
    ObjectType()
], CreateReportResultType);
export { CreateReportResultType };
let ReportResolverExtended = class ReportResolverExtended {
    async GetReportData(ReportID, context) {
        const provider = GetReadOnlyProvider(context.providers, { allowFallbackToReadWrite: true });
        const rp = new RunReport(provider);
        const result = await rp.RunReport({ ReportID: ReportID });
        return {
            ReportID: ReportID,
            Success: result.Success,
            Results: JSON.stringify(result.Results),
            RowCount: result.RowCount,
            ExecutionTime: result.ExecutionTime,
            ErrorMessage: result.ErrorMessage,
        };
    }
    async CreateReportFromConversationDetailID(ConversationDetailID, { dataSource, userPayload, providers }) {
        try {
            const md = GetReadWriteProvider(providers);
            const u = UserCache.Users.find((u) => u.Email?.trim().toLowerCase() === userPayload?.email?.trim().toLowerCase());
            if (!u)
                throw new Error('Unable to find user');
            const cde = md.Entities.find((e) => e.Name === 'Conversation Details');
            if (!cde)
                throw new Error('Unable to find Conversation Details Entity metadata');
            const cd = md.Entities.find((e) => e.Name === 'Conversations');
            if (!cd)
                throw new Error('Unable to find Conversations Entity metadata');
            const sql = `SELECT
                      cd.Message, cd.ConversationID, c.DataContextID
                   FROM
                      ${cde.SchemaName}.${cde.BaseView} cd
                   INNER JOIN
                      ${cd.SchemaName}.${cd.BaseView} c
                   ON
                      cd.ConversationID = c.ID
                   WHERE
                      cd.ID='${ConversationDetailID}'`;
            const request = new mssql.Request(dataSource);
            const result = await request.query(sql);
            if (!result || !result.recordset || result.recordset.length === 0)
                throw new Error('Unable to retrieve converation details');
            const skipData = JSON.parse(result.recordset[0].Message);
            const report = await md.GetEntityObject('Reports', u);
            report.NewRecord();
            const title = skipData.title ? skipData.title : skipData.reportTitle ? skipData.reportTitle : 'Untitled Report';
            report.Name = title;
            report.Description = skipData.userExplanation ? skipData.userExplanation : '';
            report.ConversationID = result.recordset[0].ConversationID;
            report.ConversationDetailID = ConversationDetailID;
            const dc = new DataContext();
            await dc.LoadMetadata(result.recordset[0].DataContextID, u);
            const newDataContext = await DataContext.Clone(dc, false, u);
            if (!newDataContext)
                throw new Error('Error cloning data context');
            report.DataContextID = newDataContext.ID;
            skipData.messages = [];
            report.Configuration = JSON.stringify(skipData);
            report.SharingScope = 'None';
            report.UserID = u.ID;
            if (await report.Save()) {
                return {
                    ReportID: report.ID,
                    ReportName: report.Name,
                    Success: true,
                    ErrorMessage: '',
                };
            }
            else {
                return {
                    ReportID: '',
                    ReportName: '',
                    Success: false,
                    ErrorMessage: 'Unable to save new report',
                };
            }
        }
        catch (ex) {
            const err = z.object({ message: z.string() }).safeParse(ex);
            return {
                ReportID: '',
                ReportName: '',
                Success: false,
                ErrorMessage: 'Unable to create new report: ' + err.success ? err.data.message : String(ex),
            };
        }
    }
};
__decorate([
    Query(() => RunReportResultType),
    __param(0, Arg('ReportID', () => String)),
    __param(1, Ctx()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object]),
    __metadata("design:returntype", Promise)
], ReportResolverExtended.prototype, "GetReportData", null);
__decorate([
    Mutation(() => CreateReportResultType),
    __param(0, Arg('ConversationDetailID', () => String)),
    __param(1, Ctx()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object]),
    __metadata("design:returntype", Promise)
], ReportResolverExtended.prototype, "CreateReportFromConversationDetailID", null);
ReportResolverExtended = __decorate([
    Resolver(RunReportResultType)
], ReportResolverExtended);
export { ReportResolverExtended };
//# sourceMappingURL=ReportResolver.js.map