CREATE SCHEMA covscanrest;

GRANT USAGE ON SCHEMA covscanrest TO postgres;

CREATE TABLE IF NOT EXISTS covscanrest.offerings(
    offeringId VARCHAR(100),
    description VARCHAR(200),
    PRIMARY KEY (offeringId)
);

CREATE TABLE IF NOT EXISTS covscanrest.results(
    resultsId SERIAL,
    datetime TIMESTAMP WITHOUT TIME ZONE DEFAULT (NOW() AT TIME ZONE 'utc') NOT NULL,
    state BOOLEAN,
    logs bytea,
    task_reference VARCHAR(50),
    PRIMARY KEY (resultsId)
);


CREATE TABLE IF NOT EXISTS covscanrest.scans(
    scanID SERIAL,
    offeringId VARCHAR(100),
    eventID VARCHAR(100) NOT NULL,
    isManagedService BOOLEAN NOT NULL,
    componentList VARCHAR(100),
    datetime TIMESTAMP WITHOUT TIME ZONE DEFAULT (NOW() AT TIME ZONE 'utc') NOT NULL,
    owner VARCHAR(50) NOT NULL,
    results SERIAL,
    status VARCHAR (50) CONSTRAINT valid_status CHECK(status in ('PENDING', 'DELETED', 'COMPLETED', 'IN PROGRESS')),
    last_updated TIMESTAMP WITHOUT TIME ZONE DEFAULT (NOW() AT TIME ZONE 'utc') NOT NULL,
    PRIMARY KEY(scanID),
    FOREIGN KEY (offeringId) REFERENCES covscanrest.offerings(offeringId),
    FOREIGN KEY (results) REFERENCES covscanrest.results(resultsId)
);

CREATE TABLE IF NOT EXISTS covscanrest.archive(
    scanID SERIAL,
    offeringId VARCHAR(100),
    eventID VARCHAR(100) NOT NULL,
    isManagedService BOOLEAN NOT NULL,
    componentList VARCHAR(100),
    datetime TIMESTAMP WITHOUT TIME ZONE DEFAULT (NOW() AT TIME ZONE 'utc') NOT NULL,
    owner VARCHAR(50) NOT NULL,
    results SERIAL,
    status VARCHAR (50) CONSTRAINT valid_status CHECK(status in ('PENDING', 'DELETED', 'COMPLETED', 'IN PROGRESS')),
    last_updated TIMESTAMP WITHOUT TIME ZONE DEFAULT (NOW() AT TIME ZONE 'utc') NOT NULL,
    PRIMARY KEY(scanID),
    FOREIGN KEY (offeringId) REFERENCES covscanrest.offerings(offeringId),
    FOREIGN KEY (results) REFERENCES covscanrest.results(resultsId)
);

CREATE TABLE IF NOT EXISTS covscanrest.gitscans (
    id SERIAL,
    buildSystemType VARCHAR(80),
    repository VARCHAR(150),
    reference VARCHAR(100),
    commitId VARCHAR(100),
    -- SHA256 has a length of 256 bits, so 256 bits would represent 64 hex characters
    hashsum VARCHAR(64),
    PRIMARY KEY(id)
);

CREATE TABLE IF NOT EXISTS covscanrest.pncscans(
    id SERIAL,
    buildSystemType VARCHAR(80),
    buildId VARCHAR(100),
    PRIMARY KEY(id)
);

CREATE TABLE IF NOT EXISTS covscanrest.brewscans(
    id SERIAL,
    buildSystemType VARCHAR(80),
    brewId VARCHAR(100),
    brewNVR VARCHAR(100),
    pncId VARCHAR(100),
    artifactType VARCHAR(100),
    fileName VARCHAR(100),
    builtfromSource BOOLEAN,
    PRIMARY KEY(id)
);