-- Create a schema handling trial history.
CREATE SCHEMA history;

--Create role for anyone who needs to both select and insert on historical data
CREATE ROLE history_writer;
GRANT CONNECT ON DATABASE aact_db to history_writer;

GRANT USAGE ON SCHEMA history TO history_writer;

GRANT INSERT,SELECT ON ALL TABLES IN SCHEMA http TO history_writer;


--Create role for anyone who only needs selection access to historical data, such as for analysis
CREATE ROLE history_reader;
GRANT CONNECT ON DATABASE aact_db to history_reader;

GRANT USAGE ON SCHEMA history TO history_reader;

GRANT SELECT ON ALL TABLES IN SCHEMA http TO history_reader;


/* History Tables
Below is where I would construct the parsed trial history tables that I need.

Possible fields
    nct_id
    version
    --Study Status
    overall_status^
    primary_completion_date^
    completion_date^
    last_update_submitted_date
    --SponsorCollaborators
    sponsor (multi?)
    collaborators (multi?)
    --Oversight
    fda_regulated_drug (ignore)
    fda_regulated_device (ignore)
    dmc (ignore)
    --StuldyDescription
    summary    
    detailed_description
    --Conditions
    Conditions
    Keywords
    --StudyDesign
    Study type
    Primary Purpose
    Study Phase
    Interventional Study Model
    Number of Arms
    Masking
    Allocation
    Enrollment  ^
    --ArmsAndInterventions
    Arms (multiple) (Ignore)
    --ProtocolOutcomeMeasures
    --Eligibility
    --ContactsLocation
    --IPDSharing
    --References
    --ParticipantFlow
    --BaselineCharacteristics
    --ROutcomeMeasures
    --AdverseEvents
    --LimitationsAndCaveats
    --More Information

*/

CREATE TYPE history.updatable_catetories AS ENUM
    ('Actual', 'Anticipated', 'Expected');

ALTER TYPE history.updatable_catetories
    OWNER TO root;

COMMENT ON TYPE history.updatable_catetories
    IS 'This enum is used to capture the different types of categories that a date or enrollemnt figure may have.';



CREATE TYPE history.study_statuses AS ENUM
    ('Available', 'Withdrawn', 'Withheld', 'Temporarily not available', 'Active, not recruiting', 'Recruiting', 'Not yet recruiting', 'Enrolling by invitation', 'Suspended', 'No longer available', 'Approved for marketing', 'Unknown status', 'Completed', 'Terminated');

ALTER TYPE history.study_statuses
    OWNER TO root;

COMMENT ON TYPE history.study_statuses
    IS 'This enum is used to record study status. These are pulled from the ClinicalTrials.gov documentation.';


-- Table: history.trial_snapshots

DROP TABLE IF EXISTS history.trial_snapshots;

CREATE TABLE IF NOT EXISTS history.trial_snapshots
(
    nct_id character varying(15) COLLATE pg_catalog."default" NOT NULL,
    version integer NOT NULL,
    submission_date timestamp NOT NULL,
    primary_completion_date timestamp without time zone,
    primary_completion_date_category history.updatable_catetories,
    start_date timestamp without time zone,
    start_date_category history.updatable_catetories,
    completion_date timestamp without time zone,
    completion_date_category history.updatable_catetories,
    overall_status history.study_statuses,
    enrollment integer,
    enrollment_category history.updatable_catetories,
    sponsor character varying COLLATE pg_catalog."default",
    responsible_party character varying COLLATE pg_catalog."default",
    CONSTRAINT trial_snapshots_pkey PRIMARY KEY (nct_id, version)
);


ALTER TABLE IF EXISTS history.trial_snapshots
    OWNER to root;


CREATE OR REPLACE VIEW history.match_drugs_to_trials
AS SELECT bi.nct_id,
    rp.rxcui,
    rp.propvalue1
   FROM ctgov.browse_interventions bi
     JOIN rxnorm_migrated.rxnorm_props rp ON bi.downcase_mesh_term::text = rp.propvalue1::text
  WHERE rp.propname::text = 'RxNorm Name'::text AND (bi.nct_id::text IN ( SELECT trial_snapshots.nct_id
           FROM history.trial_snapshots));