"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.EpicFhirR4Client = void 0;
const axios_1 = __importStar(require("axios"));
const lodash_1 = require("lodash");
const generateJWT_1 = require("../auth/generateJWT");
/**
 * FHIR R4 API Client
 */
class EpicFhirR4Client {
    constructor({ baseUrl, authUrl, clientId, privateKey, kid, jku, }) {
        this.accessToken = null;
        this.tokenExpiry = null; // Store token expiry time in UNIX timestamp
        this.authUrl = authUrl;
        this.clientId = clientId;
        this.privateKey = privateKey;
        this.kid = kid;
        this.jku = jku;
        this.client = axios_1.default.create({
            baseURL: new URL('FHIR/R4/', (0, lodash_1.endsWith)(baseUrl, '/') ? baseUrl : `${baseUrl}/`).toString(),
            headers: new axios_1.AxiosHeaders({
                'Content-Type': 'application/json',
            }),
        });
        this.client.interceptors.request.use(async (config) => {
            var _a;
            if ((0, lodash_1.isNil)(this.accessToken) || this.isTokenExpired()) {
                await this.refreshAccessToken();
            }
            // Add the Authorization header to the request
            if (!(0, lodash_1.isNil)(this.accessToken)) {
                config.headers = axios_1.AxiosHeaders.from((_a = config === null || config === void 0 ? void 0 : config.headers) !== null && _a !== void 0 ? _a : {});
                config.headers.set('Authorization', `Bearer ${this.accessToken}`);
            }
            return config;
        });
    }
    async refreshAccessToken() {
        try {
            const tokenResponse = await axios_1.default.post(this.authUrl, {
                grant_type: 'client_credentials',
                client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
                client_assertion: (0, generateJWT_1.generateJWT)({
                    clientId: this.clientId,
                    tokenEndpoint: this.authUrl,
                    privateKey: this.privateKey,
                    kid: this.kid,
                    jku: this.jku,
                }),
            }, {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
            });
            this.accessToken = tokenResponse.data.access_token;
            this.tokenExpiry =
                Math.floor(Date.now() / 1000) + tokenResponse.data.expires_in; // Current time + expiry
        }
        catch (error) {
            console.error('Failed to refresh access token:', error);
            throw new Error('Unable to refresh access token');
        }
    }
    isTokenExpired() {
        const now = Math.floor(Date.now() / 1000); // Current time in seconds
        return ((0, lodash_1.isNil)(this.tokenExpiry) || now >= this.tokenExpiry - 60 // Refresh 1 minute before expiry
        );
    }
    async getPatient(resourceId) {
        const url = new URL(`Patient/${resourceId}`, this.client.defaults.baseURL);
        const response = await this.client.get(url.toString());
        return response;
    }
    async createPatient(data) {
        const url = new URL(`Patient`, this.client.defaults.baseURL);
        const response = await this.client.post(url.toString(), data);
        return response;
    }
    async matchPatient(data) {
        const url = new URL(`Patient/$match`, this.client.defaults.baseURL);
        const response = await this.client.post(url.toString(), data);
        return response;
    }
    async searchPatient(data) {
        const url = new URL(`Patient`, this.client.defaults.baseURL);
        const response = await this.client.get(`${url.toString()}?identifier=MRN|${data.MRN}`);
        return response;
    }
    async createDocumentReference(data) {
        const url = new URL(`DocumentReference`, this.client.defaults.baseURL);
        const response = await this.client.post(url.toString(), data);
        return response;
    }
    async getDocumentReference(resourceId) {
        const url = new URL(`DocumentReference/${resourceId}`, this.client.defaults.baseURL);
        const response = await this.client.get(url.toString());
        return response;
    }
    async searchDocumentReferences({ patientResourceId, category, }) {
        const url = new URL(`DocumentReference`, this.client.defaults.baseURL);
        const queryParams = new URLSearchParams();
        queryParams.set('patient', patientResourceId);
        if (category !== undefined) {
            queryParams.set('category', category);
        }
        url.search = queryParams.toString();
        const response = await this.client.get(url.toString());
        return response;
    }
    async getAppointment(resourceId) {
        const url = new URL(`Appointment/${resourceId}`, this.client.defaults.baseURL);
        const response = await this.client.get(url.toString());
        return response;
    }
    async getBinary(resourceId) {
        const url = new URL(`Binary/${resourceId}`, this.client.defaults.baseURL);
        const response = await this.client.get(url.toString());
        return response;
    }
    async getMetadata() {
        const url = new URL(`metadata`, this.client.defaults.baseURL);
        const response = await this.client.get(url.toString());
        return response;
    }
}
exports.EpicFhirR4Client = EpicFhirR4Client;
//# sourceMappingURL=FhirR4client.js.map