CREATE TABLE files (
    key TEXT PRIMARY KEY,
    data BYTEA NOT NULL
);

CREATE SEQUENCE tasks_data_id_seq START WITH 1 INCREMENT BY 1;

CREATE TABLE tasks (
    data_id BIGINT PRIMARY KEY DEFAULT nextval('tasks_data_id_seq'),
    id TEXT NOT NULL,
    in_game_id TEXT NOT NULL,
    boss_app_id TEXT NOT NULL,
    creator_user TEXT NOT NULL,
    status TEXT NOT NULL,
    interval INTEGER NOT NULL,
    title_id TEXT NOT NULL,
    description TEXT NOT NULL,
    deleted BOOLEAN NOT NULL DEFAULT FALSE,
    created TIMESTAMP NOT NULL,
    updated TIMESTAMP NOT NULL
);

CREATE SEQUENCE files_wup_data_id_seq START WITH 50000 INCREMENT BY 1;

CREATE TABLE files_wup (
    data_id BIGINT PRIMARY KEY DEFAULT nextval('files_wup_data_id_seq'),
    file_key TEXT NOT NULL,
    task_id TEXT NOT NULL,
    boss_app_id TEXT NOT NULL,
    supported_countries TEXT[] NOT NULL,
    supported_languages TEXT[] NOT NULL,
    attributes JSONB NOT NULL,
    creator_user TEXT NOT NULL,
    name TEXT NOT NULL,
    type TEXT NOT NULL,
    hash TEXT NOT NULL,
    size BIGINT NOT NULL,
    notify_on_new TEXT[] NOT NULL,
    notify_led BOOLEAN NOT NULL,
    condition_played BIGINT NOT NULL,
    auto_delete BOOLEAN NOT NULL,
    deleted BOOLEAN NOT NULL DEFAULT FALSE,
    created TIMESTAMP NOT NULL,
    updated TIMESTAMP NOT NULL
);

CREATE OR REPLACE FUNCTION files_wup_set_name_from_data_id()
RETURNS trigger AS $$
BEGIN
    IF NEW.name IS NULL OR NEW.name = '' THEN
        NEW.name := NEW.data_id::text;
    END IF;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER files_wup_set_name
BEFORE INSERT ON files_wup
FOR EACH ROW
EXECUTE FUNCTION files_wup_set_name_from_data_id();
