CREATE TABLE IF NOT EXISTS MUTABILITY (ID INT PRIMARY KEY, MUTABILITY TEXT);
CREATE TABLE IF NOT EXISTS DATATYPE (ID INT PRIMARY KEY, DATATYPE TEXT);

CREATE TABLE CONFIG_META (
    ID INTEGER PRIMARY KEY,
    LAST_UPDATED TEXT NOT NULL,
    VALID TEXT INTEGER NOT NULL,
    CONFIG_DUMP TEXT NOT NULL,
    CONFIG_FILE_PATH TEXT
);

CREATE TABLE IF NOT EXISTS SETTING (
  ID INTEGER PRIMARY KEY CHECK (id = 0),
  PREFIX TEXT NOT NULL,
  CONFIG_FILE TEXT NOT NULL,
  CONFIGS_DIR TEXT NOT NULL,
  SCHEMAS_DIR TEXT NOT NULL,
  MODULES_DIR TEXT NOT NULL,
  INTERFACES_DIR TEXT NOT NULL,
  TYPES_DIR TEXT NOT NULL,
  ERRORS_DIR TEXT NOT NULL,
  WWW_DIR TEXT NOT NULL,
  LOGGING_CONFIG_FILE TEXT NOT NULL,
  CONTROLLER_PORT INTEGER NOT NULL,
  CONTROLLER_RPC_TIMEOUT_MS INTEGER NOT NULL,
  MQTT_BROKER_SOCKET_PATH TEXT NOT NULL,
  MQTT_BROKER_HOST TEXT NOT NULL,
  MQTT_BROKER_PORT INTEGER NOT NULL,
  MQTT_EVEREST_PREFIX TEXT NOT NULL,
  MQTT_EXTERNAL_PREFIX TEXT NOT NULL,
  TELEMETRY_PREFIX TEXT NOT NULL,
  TELEMETRY_ENABLED INTEGER NOT NULL,
  VALIDATE_SCHEMA INTEGER NOT NULL,
  RUN_AS_USER TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS MODULE (
    ID TEXT PRIMARY KEY,
    NAME TEXT NOT NULL,
    STANDALONE INTEGER,
    CAPABILITIES TEXT
);

CREATE TABLE IF NOT EXISTS MODULE_FULFILLMENT (
  MODULE_ID TEXT,
  REQUIREMENT_NAME TEXT NOT NULL,
  IMPLEMENTATION_ID TEXT NOT NULL,
  IMPLEMENTATION_MODULE_ID TEXT NOT NULL,
  PRIMARY KEY (MODULE_ID, REQUIREMENT_NAME, IMPLEMENTATION_ID, IMPLEMENTATION_MODULE_ID),
  FOREIGN KEY (MODULE_ID) REFERENCES MODULE (ID) ON DELETE CASCADE,
  FOREIGN KEY (IMPLEMENTATION_MODULE_ID)  REFERENCES MODULE (ID) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS MODULE_TIER_MAPPING (
  MODULE_ID TEXT,
  IMPLEMENTATION_ID TEXT NOT NULL,
  EVSE_ID INTEGER NOT NULL,
  CONNECTOR_ID INTEGER,
  PRIMARY KEY (MODULE_ID, IMPLEMENTATION_ID),
  FOREIGN KEY (MODULE_ID) REFERENCES MODULE (ID) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS CONFIGURATION (
    PARAMETER_NAME TEXT,
    MODULE_ID TEXT NOT NULL,
    MODULE_IMPLEMENTATION_ID TEXT NOT NULL,
    "VALUE" TEXT NOT NULL,
    MUTABILITY_ID INTEGER NOT NULL,
    DATATYPE_ID INTEGER NOT NULL,
    UNIT TEXT,
    SOURCE TEXT,
    PRIMARY KEY (MODULE_ID, PARAMETER_NAME, MODULE_IMPLEMENTATION_ID),
    FOREIGN KEY (MODULE_ID) REFERENCES MODULE (ID) ON DELETE CASCADE,
    FOREIGN KEY (DATATYPE_ID) REFERENCES DATATYPE (ID) ON DELETE RESTRICT,
    FOREIGN KEY (MUTABILITY_ID) REFERENCES MUTABILITY (ID) ON DELETE RESTRICT
);

INSERT OR REPLACE INTO MUTABILITY (ID, MUTABILITY) VALUES 
  (0, "ReadOnly"),
  (1, "WriteOnly"),
  (2, "ReadWrite");
INSERT
  OR REPLACE INTO DATATYPE VALUES 
  (0, "string"),
  (1, "decimal"),
  (2, "integer"),
  (3, "boolean");
INSERT 
  OR IGNORE INTO SETTING (ID)
VALUES (0);

