""" Module for extracting US core extensions from medicationrequests

Note: This module assumes that you have already run builder_medication,
as it leverages the core__medication table for data population"""

from cumulus_library import base_table_builder, databases
from cumulus_library.studies.core.core_templates import core_templates
from cumulus_library.template_sql import sql_utils

expected_table_cols = {
    "medicationrequest": {
        "id": [],
        "status": [],
        "intent": [],
        "authoredOn": [],
        "reportedBoolean": [],
        "category": ["code", "system", "display"],
        "medicationCodeableConcept": ["code", "system", "display"],
        "subject": ["reference"],
        "encounter": ["reference"],
        "dosageInstruction": ["text"],
    }
}


class MedicationRequestBuilder(base_table_builder.BaseTableBuilder):
    display_text = "Creating MedicationRequest tables..."

    def prepare_queries(
        self,
        cursor: object,
        schema: str,
        *args,
        parser: databases.DatabaseParser = None,
        **kwargs,
    ):
        """constructs queries related to patient extensions of interest

        :param cursor: A database cursor object
        :param schema: the schema/db name, matching the cursor
        """
        code_sources = [
            sql_utils.CodeableConceptConfig(
                source_table="medicationrequest",
                source_id="id",
                column_hierarchy=[("category", list)],
                target_table="core__medicationrequest_dn_category",
            ),
            sql_utils.CodeableConceptConfig(
                source_table="medicationrequest",
                source_id="id",
                column_hierarchy=[("medicationcodeableconcept", dict)],
                target_table="core__medicationrequest_dn_medication",
            ),
        ]
        self.queries += sql_utils.denormalize_complex_objects(
            schema, cursor, code_sources
        )
        validated_schema = core_templates.validate_schema(
            cursor, schema, expected_table_cols, parser
        )
        self.queries.append(
            core_templates.get_core_template("medicationrequest", validated_schema)
        )
