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 '@akago/vine-lucid';
import vine, { errors } from '@vinejs/vine';
import '../../lib/vine_types/vine_sirene.js';
import { AKVineRequestQuery, AKVineResponse } from '../crud/vine_handler_decorators.js';
import { AKVineRequestData } from '../crud/vine_validate_middleware.js';
import { OpenApiDescription, OpenApiName } from '../openapi/openapi_router_macros.js';
import AKInseeService from './insee_service.js';
import { AKInseeCompanyVineSchema } from './schema.js';
export default class AKInseeController {
    async handle(_ctx, inseeService, { q: query }) {
        if (/^[0-9 ]+$/.test(query))
            query = query.replace(/ /g, '');
        try {
            await vine.compile(AKInseeCompanyVineSchema.siret).validate(query);
            return [await inseeService.findBySiret(query)];
        }
        catch (e) {
            if (e instanceof errors.E_VALIDATION_ERROR) {
                try {
                    await vine.compile(vine.string().siren()).validate(query);
                    return [await inseeService.findBySiren(query)];
                }
                catch (e) {
                    if (e instanceof errors.E_VALIDATION_ERROR) {
                        await vine.compile(AKInseeCompanyVineSchema.name).validate(query);
                        return await inseeService.findByName(query);
                    }
                    else
                        throw e;
                }
            }
            else
                throw e;
        }
    }
}
__decorate([
    OpenApiName(`Search company (INSEE)`),
    OpenApiDescription(`Searches company in INSEE database based on \`q\` in query parameters. Searches in order : siret, siren, name`),
    AKVineRequestQuery(vine.object({ q: vine.string() })),
    AKVineResponse(vine.array(vine.object(AKInseeCompanyVineSchema))),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Function, AKInseeService, AKVineRequestData]),
    __metadata("design:returntype", Promise)
], AKInseeController.prototype, "handle", null);
//# sourceMappingURL=insee_controller.js.map