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 { ResponseStatus } from '@adonisjs/core/http';
import _ from 'lodash';
import { request } from 'undici';
import { AKAPIException } from '../exceptions/api_exception.js';
import { method } from '../observability/tracing.js';
export default class AKInseeService {
    options;
    base_url = 'https://api.insee.fr/api-sirene/3.11/';
    constructor(options) {
        this.options = options;
    }
    async #fetchFromSireneAPI(siret, params) {
        try {
            const { body } = await request(this.base_url + (siret ? 'siret/' + siret : 'siret'), {
                query: params,
                headers: {
                    'X-INSEE-Api-Key-Integration': this.options.apiKey,
                },
            });
            const resp = (await body.json());
            return resp;
        }
        catch (e) {
            if (e.status === ResponseStatus.NotFound)
                return undefined;
            else
                throw AKAPIException.notAvailable;
        }
    }
    async findBySiret(siret) {
        const res = await this.#fetchFromSireneAPI(siret);
        if (res) {
            const data = res['etablissement'];
            if (!this.#isCompanyValid(data))
                throw AKAPIException.doesNotExist;
            else
                return this.#parseCompany(data);
        }
        throw AKAPIException.doesNotExist;
    }
    async findBySiren(siren) {
        const params = { q: 'siren:' + siren, tri: 'siret desc' };
        const res = await this.#fetchFromSireneAPI(undefined, params);
        if (res) {
            const data = _.head(res['etablissements']);
            if (!this.#isCompanyValid(data))
                throw AKAPIException.doesNotExist;
            else
                return this.#parseCompany(data);
        }
        throw AKAPIException.doesNotExist;
    }
    async findByName(query) {
        const combinaisons = [
            ['denominationUniteLegale'],
            ['nomUniteLegale', 'prenom1UniteLegale', 'prenom2UniteLegale', 'prenom3UniteLegale'],
            ['prenom1UniteLegale', 'nomUniteLegale'],
        ];
        const limitArray = (array, length, joiner) => [
            ..._.take(array, length - 1),
            _.takeRight(array, array.length - length + 1).join(joiner),
        ];
        const q = _(combinaisons)
            .map((comb) => _(comb)
            .zipWith(limitArray(query.split(' '), comb.length, ' '), (k, v) => v ? [k, v] : undefined)
            .filter(_.negate(_.isUndefined))
            .map(([k, v]) => `${k}:"${v}"~`)
            .join(' AND '))
            .map((q) => `(${q})`)
            .join(' OR ');
        const res = await this.#fetchFromSireneAPI(undefined, { q, tri: 'siret desc' });
        return _(res ? res['etablissements'] : undefined)
            .filter(this.#isCompanyValid)
            .map(this.#parseCompany)
            .value();
    }
    #isCompanyValid(data) {
        if (!data)
            return false;
        if (data['uniteLegale']['etatAdministratifUniteLegale'] === 'C')
            return false;
        if (data['periodesEtablissement'].find((p) => p.dateFin === null)?.['etatAdministratifEtablissement'] === 'F')
            return false;
        return true;
    }
    #parseCompany(data) {
        const address = data['adresseEtablissement'];
        const ul = data['uniteLegale'];
        const name = ul['denominationUniteLegale'] ||
            _(['nomUniteLegale', 'prenom1UniteLegale', 'prenom2UniteLegale', 'prenom3UniteLegale'])
                .map((k) => ul[k])
                .filter(_.negate(_.isUndefined))
                .join(' ');
        const sireneInfoIsPublic = data['statutDiffusionEtablissement'] === 'O';
        return {
            name: sireneInfoIsPublic ? name : null,
            sireneInfoIsPublic,
            siret: data['siret'],
            siren: data['siren'],
            postalCode: sireneInfoIsPublic ? (address['codePostalEtablissement'] ?? null) : null,
            city: address['libelleCommuneEtablissement'] ?? null,
            address: sireneInfoIsPublic
                ? [address['numeroVoieEtablissement'], address['typeVoieEtablissement'], address['libelleVoieEtablissement']]
                    .filter(Boolean)
                    .join(' ') || null
                : null,
        };
    }
}
__decorate([
    method(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], AKInseeService.prototype, "findBySiret", null);
__decorate([
    method(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], AKInseeService.prototype, "findBySiren", null);
__decorate([
    method(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], AKInseeService.prototype, "findByName", null);
//# sourceMappingURL=insee_service.js.map