-- +goose Up
-- +goose StatementBegin
CREATE TABLE subreddits (
    name VARCHAR(30) NOT NULL PRIMARY KEY COLLATE NOCASE,
    disable_scheduler TINYINT NOT NULL DEFAULT 0,
    "type" VARCHAR(5) NOT NULL DEFAULT 'r',
    schedule VARCHAR(20) NOT NULL DEFAULT '@daily',
    countback INT NOT NULL DEFAULT 300,
    image_cover VARCHAR(255) NOT NULL DEFAULT '',
    created_at BIGINT DEFAULT (strftime('%s', 'now')) NOT NULL,
    updated_at BIGINT DEFAULT (strftime('%s', 'now')) NOT NULL
);

CREATE UNIQUE INDEX idx_subreddits_name ON subreddits(name);

CREATE TRIGGER subreddits_update_timestamp AFTER UPDATE ON subreddits FOR EACH ROW
BEGIN
    UPDATE subreddits SET updated_at = (strftime('%s', 'now')) WHERE name = old.name;
END;

CREATE TRIGGER subreddits_insert_create_total_image_metrics AFTER INSERT on subreddits FOR EACH ROW
BEGIN
    INSERT INTO metrics (name, value)
    VALUES (CONCAT('subreddits.', NEW.name, '.total_images'), 0);
END;

CREATE TRIGGER subreddits_delete_total_image_metrics AFTER DELETE on subreddits FOR EACH ROW
BEGIN
    DELETE FROM metrics WHERE name = CONCAT('subreddits.', OLD.name, '.total_images');
END;
-- +goose StatementEnd

-- +goose Down
-- +goose StatementBegin
DROP TABLE subreddits;
-- +goose StatementEnd
