"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get makeCovidCertificate () {
        return makeCovidCertificate;
    },
    get makeCovidVaccineCertificate () {
        return makeCovidVaccineCertificate;
    },
    get makeVaccineCertificate () {
        return makeVaccineCertificate;
    }
});
const _react = /*#__PURE__*/ _interop_require_default(require("react"));
const _config = /*#__PURE__*/ _interop_require_default(require("config"));
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _lodash = require("lodash");
const _renderer = /*#__PURE__*/ _interop_require_default(require("@react-pdf/renderer"));
const _constants = require("@tamanu/constants");
const _timeZoneCheck = require("@tamanu/shared/utils/timeZoneCheck");
const _utils = require("@tamanu/shared/utils");
const _patientCertificates = require("@tamanu/shared/utils/patientCertificates");
const _localisation = require("../localisation");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
async function getCertificateAssets(models, footerAssetName) {
    const footerAsset = await models.Asset.findOne({
        raw: true,
        where: {
            name: footerAssetName,
            facilityId: null
        }
    });
    const footerAssetData = footerAsset?.data;
    const [logo, watermark, signingImage] = (await Promise.all([
        _constants.ASSET_NAMES.LETTERHEAD_LOGO,
        _constants.ASSET_NAMES.VACCINE_CERTIFICATE_WATERMARK,
        ...footerAsset?.data ? [] : [
            _constants.ASSET_FALLBACK_NAMES[footerAssetName] || _constants.ASSET_NAMES.CERTIFICATE_BOTTOM_HALF_IMG
        ]
    ].map((name)=>name && models.Asset.findOne({
            raw: true,
            where: {
                name,
                facilityId: null
            }
        })))).map((record)=>record?.data);
    return {
        logo,
        signingImage: footerAssetData || signingImage,
        watermark
    };
}
async function renderPdf(element, fileName) {
    const folder = await (0, _utils.tmpdir)();
    const filePath = _path.default.join(folder, fileName);
    await _renderer.default.render(element, filePath);
    return {
        status: 'success',
        filePath
    };
}
async function getPatientVaccines(models, patient) {
    const { data: vaccines } = await patient.getAdministeredVaccines({
        order: [
            [
                'date',
                'ASC'
            ]
        ],
        includeNotGiven: false
    });
    const vaccineData = vaccines.filter((vaccine)=>!vaccine.scheduledVaccine.hideFromCertificate);
    const certifiableVaccines = vaccineData.filter((vaccine)=>vaccine.certifiable);
    const additionalData = await models.PatientAdditionalData.findOne({
        where: {
            patientId: patient.id
        },
        include: models.PatientAdditionalData.getFullReferenceAssociations()
    });
    const village = await models.ReferenceData.findByPk(patient.villageId, {});
    const patientData = {
        ...patient.dataValues,
        village,
        additionalData: additionalData?.dataValues
    };
    return {
        certifiableVaccines,
        vaccines: vaccineData,
        patientData
    };
}
const makeCovidVaccineCertificate = async ({ models, settings, language, patient, printedBy, printedDate })=>{
    const [localisation, settingsObj] = await Promise.all([
        (0, _localisation.getLocalisation)(),
        settings.getAll()
    ]);
    const getLocalisationData = (key)=>(0, _lodash.get)(localisation, key);
    const getSettingData = (key)=>(0, _lodash.get)(settingsObj, key);
    const fileName = `covid-vaccine-certificate-${patient.id}.pdf`;
    const { logo, signingImage, watermark } = await getCertificateAssets(models, _constants.ASSET_NAMES.COVID_VACCINATION_CERTIFICATE_FOOTER);
    const { certifiableVaccines, patientData } = await getPatientVaccines(models, patient);
    return renderPdf(/*#__PURE__*/ _react.default.createElement(_utils.CovidVaccineCertificate, {
        patient: patientData,
        printedBy: printedBy,
        printedDate: printedDate,
        vaccinations: certifiableVaccines,
        signingSrc: signingImage,
        watermarkSrc: watermark,
        logoSrc: logo,
        getLocalisation: getLocalisationData,
        getSetting: getSettingData,
        primaryTimeZone: (0, _timeZoneCheck.getPrimaryTimeZone)(_config.default),
        language: language
    }), fileName);
};
const makeVaccineCertificate = async ({ models, settings, facilityName, language, patient, printedBy, printedDate, translations })=>{
    const [localisation, settingsObj] = await Promise.all([
        (0, _localisation.getLocalisation)(),
        settings.getAll()
    ]);
    const getSettingData = (key)=>(0, _lodash.get)(settingsObj, key);
    const { title, subTitle } = await settings.get('templates.letterhead');
    const { healthFacility } = await settings.get('templates.vaccineCertificate');
    const fileName = `vaccine-certificate-${patient.id}.pdf`;
    const { logo, signingImage, watermark } = await getCertificateAssets(models, _constants.ASSET_NAMES.VACCINATION_CERTIFICATE_FOOTER);
    const { vaccines, patientData } = await getPatientVaccines(models, patient);
    return renderPdf(/*#__PURE__*/ _react.default.createElement(_utils.VaccineCertificate, {
        patient: patientData,
        printedBy: printedBy,
        printedDate: printedDate,
        vaccinations: vaccines,
        facilityName: facilityName,
        signingSrc: signingImage,
        watermarkSrc: watermark,
        logoSrc: logo,
        translations: translations,
        localisation: localisation,
        language: language,
        certificateData: {
            title,
            subTitle
        },
        healthFacility: healthFacility,
        getSetting: getSettingData,
        primaryTimeZone: (0, _timeZoneCheck.getPrimaryTimeZone)(_config.default)
    }), fileName);
};
const makeCovidCertificate = async ({ models, settings, certType, language, patient, printedBy })=>{
    const settingsObj = await settings.getAll();
    const getSettingData = (key)=>(0, _lodash.get)(settingsObj, key);
    const fileName = `covid-${certType}-certificate-${patient.id}.pdf`;
    const footerAssetName = certType === _patientCertificates.CertificateTypes.test ? _constants.ASSET_NAMES.COVID_TEST_CERTIFICATE_FOOTER : _constants.ASSET_NAMES.COVID_CLEARANCE_CERTIFICATE_FOOTER;
    const { logo, signingImage, watermark } = await getCertificateAssets(models, footerAssetName);
    const additionalData = await models.PatientAdditionalData.findOne({
        where: {
            patientId: patient.id
        },
        include: models.PatientAdditionalData.getFullReferenceAssociations()
    });
    const passportFromSurveyResponse = await (0, _utils.getPatientSurveyResponseAnswer)(models, patient.id, getSettingData('questionCodeIds.passport'));
    const nationalityId = await (0, _utils.getPatientSurveyResponseAnswer)(models, patient.id, getSettingData('questionCodeIds.nationalityId'));
    const nationalityRecord = await models.ReferenceData.findByPk(nationalityId);
    const nationalityFromSurveyResponse = nationalityRecord?.dataValues?.name;
    const patientData = {
        ...patient.dataValues,
        additionalData: {
            ...additionalData?.dataValues,
            passport: additionalData?.dataValues?.passport || passportFromSurveyResponse,
            nationality: {
                name: additionalData?.dataValues?.nationality?.name || nationalityFromSurveyResponse
            }
        }
    };
    const labs = certType === _patientCertificates.CertificateTypes.test ? await patient.getCovidLabTests() : await patient.getCovidClearanceLabTests();
    return renderPdf(/*#__PURE__*/ _react.default.createElement(_patientCertificates.CovidLabCertificate, {
        patient: patientData,
        labs: labs,
        signingSrc: signingImage,
        watermarkSrc: watermark,
        logoSrc: logo,
        printedBy: printedBy,
        getSetting: getSettingData,
        primaryTimeZone: (0, _timeZoneCheck.getPrimaryTimeZone)(_config.default),
        certType: certType,
        language: language
    }), fileName);
};

//# sourceMappingURL=makePatientCertificate.js.map