-- +migrate Up
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE EXTENSION IF NOT EXISTS timescaledb;

CREATE TYPE target_type AS ENUM ('service', 'infra');
CREATE TYPE check_type AS ENUM ('http', 'ping', 'tcp');
CREATE TYPE incident_status AS ENUM ('open', 'acknowledged', 'resolved');
CREATE TYPE alert_severity AS ENUM ('info', 'warning', 'critical');

CREATE TABLE targets (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    name VARCHAR(255) NOT NULL,
    type target_type NOT NULL,
    config JSONB NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE checks (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    target_id UUID NOT NULL REFERENCES targets(id) ON DELETE CASCADE,
    type check_type NOT NULL,
    interval_seconds INTEGER NOT NULL,
    timeout_seconds INTEGER NOT NULL,
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE metrics (
    time TIMESTAMPTZ NOT NULL,
    check_id UUID NOT NULL REFERENCES checks(id) ON DELETE CASCADE,
    value DOUBLE PRECISION NOT NULL,
    tags JSONB
);

-- Create a hypertable for metrics
SELECT create_hypertable('metrics', 'time');

CREATE TABLE alert_rules (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    check_id UUID NOT NULL REFERENCES checks(id) ON DELETE CASCADE,
    name VARCHAR(255) NOT NULL,
    threshold DOUBLE PRECISION NOT NULL,
    -- e.g., '>', '<', '='
    operator VARCHAR(10) NOT NULL,
    -- in seconds
    for_duration BIGINT NOT NULL,
    severity alert_severity NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE incidents (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    alert_rule_id UUID NOT NULL REFERENCES alert_rules(id) ON DELETE CASCADE,
    status incident_status NOT NULL,
    start_time TIMESTAMPTZ NOT NULL,
    end_time TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Indexes
CREATE INDEX ON checks (target_id);
CREATE INDEX ON metrics (check_id, time DESC);
CREATE INDEX ON alert_rules (check_id);
CREATE INDEX ON incidents (alert_rule_id, status);


-- +migrate Down
DROP TABLE IF EXISTS incidents;
DROP TABLE IF EXISTS alert_rules;
DROP TABLE IF EXISTS metrics;
DROP TABLE IF EXISTS checks;
DROP TABLE IF EXISTS targets;
DROP TYPE IF EXISTS incident_status;
DROP TYPE IF EXISTS alert_severity;
DROP TYPE IF EXISTS check_type;
DROP TYPE IF EXISTS target_type;
