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 string from '@adonisjs/core/helpers/string';
import { HttpContext, ResponseStatus } from '@adonisjs/core/http';
import '@akago/vine-lucid';
import vine, { errors } from '@vinejs/vine';
import { AKAPIException } from '../exceptions/api_exception.js';
import { OpenApiDescription, OpenApiName } from '../openapi/openapi_router_macros.js';
import { genericListFilters } from './services/filters/generic.js';
import { AKListFilter } from './services/filters/index.js';
import { AKVineRequest, AKVineResponse, AKVineResponseErrors, AKVineResponseStatus, } from './vine_handler_decorators.js';
import { AKVineRequestData } from './vine_validate_middleware.js';
export const modelController = (modelServiceClass) => {
    const modelService = new modelServiceClass();
    const modelNameHumanReadable = string.camelCase(string.plural(modelService.model.name));
    class AKModelController {
        modelService = modelService;
        idValidator = vine.compile(vine.lucid(modelService.model, {
            primaryKey: 'only',
        }));
        searchFields = [...modelService.model.$columnsDefinitions.keys()];
        async extraListFilters() {
            return [];
        }
        async index({ request }) {
            const { order_by: orderBy, limit, ...queryString } = request.qs();
            const listFilters = [...(await this.extraListFilters()), ...genericListFilters];
            const queryTranform = AKListFilter.parseQueryString(queryString, listFilters, this.modelService.model, this.searchFields);
            const items = await this.modelService.list({
                queryTranform,
                sortKey: orderBy,
                limit,
            });
            return items.map((item) => item.serialize());
        }
        async show({ params }) {
            const id = await this.extractIdFromParams(params);
            const item = await this.modelService.findById(id);
            if (item)
                return item.serialize();
            else
                throw AKAPIException.doesNotExist;
        }
        async store({ response }, payload) {
            const item = await this.modelService.create(payload);
            return response.created(item.serialize());
        }
        async update({ params }, payload) {
            const id = await this.extractIdFromParams(params);
            const updatedItem = await this.modelService.update(id, payload);
            return updatedItem.serialize();
        }
        async destroy({ params, response }) {
            const id = await this.extractIdFromParams(params);
            await this.modelService.delete(id);
            return response.noContent();
        }
        async extractIdFromParams(params) {
            try {
                const { id } = await this.idValidator.validate(params);
                return id;
            }
            catch (e) {
                if (e instanceof errors.E_VALIDATION_ERROR)
                    throw AKAPIException.malformedUuid;
                else
                    throw e;
            }
        }
    }
    __decorate([
        OpenApiName(`List ${modelNameHumanReadable}`),
        OpenApiDescription(`List ${modelNameHumanReadable}. You can also apply filters, see 'List filter' section.`),
        AKVineResponse(vine.array(vine.lucid(modelService.model, {
            relations: modelServiceClass.enabledRelations,
        }))),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [HttpContext]),
        __metadata("design:returntype", Promise)
    ], AKModelController.prototype, "index", null);
    __decorate([
        OpenApiName(`Get ${string.singular(modelNameHumanReadable)} by id`),
        AKVineResponseStatus(ResponseStatus.NoContent),
        AKVineResponse(vine.lucid(modelService.model, {
            relations: modelServiceClass.enabledRelations,
        })),
        AKVineResponseErrors([AKAPIException.malformedUuid]),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [HttpContext]),
        __metadata("design:returntype", Promise)
    ], AKModelController.prototype, "show", null);
    __decorate([
        OpenApiName(`Create ${string.singular(modelNameHumanReadable)}`),
        AKVineRequest(vine.lucid(modelService.model, {
            update: true,
            relations: modelServiceClass.enabledRelations,
        })),
        AKVineResponseStatus(ResponseStatus.Created),
        AKVineResponse(vine.lucid(modelService.model, {
            relations: modelServiceClass.enabledRelations,
        })),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [HttpContext, AKVineRequestData]),
        __metadata("design:returntype", Promise)
    ], AKModelController.prototype, "store", null);
    __decorate([
        OpenApiName(`Update ${string.singular(modelNameHumanReadable)}`),
        AKVineRequest(vine.lucid(modelService.model, {
            update: true,
            relations: modelServiceClass.enabledRelations,
        })),
        AKVineResponse(vine.lucid(modelService.model, {
            relations: modelServiceClass.enabledRelations,
        })),
        AKVineResponseErrors([AKAPIException.malformedUuid]),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [HttpContext, AKVineRequestData]),
        __metadata("design:returntype", Promise)
    ], AKModelController.prototype, "update", null);
    __decorate([
        OpenApiName(`Delete ${string.singular(modelNameHumanReadable)}`),
        AKVineResponseStatus(ResponseStatus.NoContent),
        AKVineResponseErrors([AKAPIException.malformedUuid, AKAPIException.doesNotExist]),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [HttpContext]),
        __metadata("design:returntype", Promise)
    ], AKModelController.prototype, "destroy", null);
    return AKModelController;
};
//# sourceMappingURL=model_controller.js.map