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);
};
import app from '@adonisjs/core/services/app';
import logger from '@adonisjs/core/services/logger';
import _ from 'lodash';
import { subpathsObject } from '../../../lib/utils.js';
import { asyncBlock, method } from '../../observability/tracing.js';
import { AKModelService } from './index.js';
export const AKModelServiceFetch = (superclass) => {
    class AKModelServiceFetch extends superclass {
        static enabledRelations = [];
        static enabledFetchRelations = [];
        async #baseQuery(includeEnabledFetchRelations = false) {
            let query = this.model.query();
            this.modifyBaseQuery(query);
            const baseRelations = this.constructor.enabledRelations ?? [];
            const fetchRelations = this.constructor.enabledFetchRelations ?? [];
            const relations = includeEnabledFetchRelations ? [...baseRelations, ...fetchRelations] : baseRelations;
            await Promise.all(_.map(relations, async (r) => await r.makeService()));
            this.preloadRelations(query, relations);
            return () => query;
        }
        async #applyListQuery(dbQuery, listQuery) {
            if (listQuery.queryTranform)
                listQuery.queryTranform(dbQuery);
            if (listQuery.sortKey)
                dbQuery.orderBy(_.trim(listQuery.sortKey, '-'), _.startsWith(listQuery.sortKey, '-') ? 'desc' : 'asc');
            if (listQuery.limit)
                dbQuery.limit(listQuery.limit);
            return () => dbQuery;
        }
        modifyBaseQuery(_query) { }
        modifyListQuery(_query) { }
        modifyFindQuery(_query) { }
        async enrichFetchResults(items) {
            return items;
        }
        async list(query) {
            return await this.baseList({
                ...query,
                queryTranform: (q) => {
                    this.modifyListQuery(q);
                    if (query.queryTranform)
                        query.queryTranform(q);
                },
            });
        }
        async baseList(query) {
            const baseQuery = (await this.#baseQuery())();
            const dbQuery = (await this.#applyListQuery(baseQuery, query))();
            const items = await dbQuery;
            return await this.enrichFetchResults(items);
        }
        async count(query) {
            const baseQuery = this.model.query();
            this.modifyBaseQuery(baseQuery);
            const dbQuery = (await this.#applyListQuery(baseQuery, query))();
            const result = await dbQuery.clearSelect().count('*', 'count');
            return Number(result[0].$extras.count) ?? 0;
        }
        async sum(query, column) {
            const baseQuery = this.model.query();
            this.modifyBaseQuery(baseQuery);
            const dbQuery = (await this.#applyListQuery(baseQuery, query))();
            const result = await dbQuery.clearSelect().sum(column, 'sum');
            return Number(result[0].$extras.sum) ?? 0;
        }
        async findBy(field, value) {
            return await this.find({ [field]: value });
        }
        async find(field) {
            if (_.isEmpty(field)) {
                return undefined;
            }
            const dbQuery = (await asyncBlock(`AKModelServiceFetchMixin<${this.model.name}>.find.buildQuery`, async () => {
                const dbQuery = (await this.#baseQuery(true))();
                this.modifyFindQuery(dbQuery);
                _.forEach(field, (value, field) => dbQuery.where(field, value));
                return () => dbQuery;
            }))();
            const itemOrNull = await asyncBlock(`AKModelServiceFetchMixin<${this.model.name}>.find.fetch`, async () => await dbQuery.first());
            const item = _.isNil(itemOrNull) ? undefined : itemOrNull;
            const enrichedItem = item
                ? await asyncBlock(`AKModelServiceFetchMixin<${this.model.name}>.find.enrich`, async () => (await this.enrichFetchResults([item]))[0])
                : item;
            return await asyncBlock(`AKModelServiceFetchMixin<${this.model.name}>.find.postFind`, async () => await this.postFind(enrichedItem));
        }
        async findById(id) {
            return await this.findBy('id', id);
        }
        async postFind(item) {
            return item;
        }
        preloadRelations(query, relations) {
            if (relations.length === 0)
                return;
            const thisname = this.constructor.name ?? this.model.name;
            const relationsNames = relations.map((r) => r.name).join(', ');
            logger.debug(`${thisname} preload relations ${relationsNames}`);
            for (const [relationKey, relationDef] of this.model.$relationsDefinitions) {
                const relationModel = relationDef.relatedModel();
                const relationOption = relations.find((r) => r.name === relationKey);
                if (relationOption)
                    query.preload(relationKey, (relationQuery) => {
                        relationOption.queryModifier?.(relationQuery);
                        const subService = relationOption.service || new (AKModelService(relationModel))();
                        const subRelations = subpathsObject(relations, relationKey, (r) => r.name, (r, name) => r.copyWithName(name));
                        subService.modifyBaseQuery(relationQuery);
                        subService.preloadRelations(relationQuery, subRelations);
                    });
                else if (relationDef.serializeAs !== null) {
                }
            }
        }
        async itemForIdInPayload(payload, serviceClass) {
            const service = await app.container.make(serviceClass);
            const model = service.model;
            const id = payload[_.lowerCase(model.name)][model.primaryKey];
            const item = await service.findBy(model.primaryKey, id);
            return item;
        }
    }
    __decorate([
        method({
            name: (_, obj) => `AKModelServiceFetchMixin<${obj.model.name}>.find`,
        }),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", Promise)
    ], AKModelServiceFetch.prototype, "find", null);
    return AKModelServiceFetch;
};
//# sourceMappingURL=fetch.js.map