CREATE TYPE scenario_name AS ENUM (
    'DISCOUNT_FOR_LOST',
    'ENGAGE_PROSPECTIVE',
    'THANK_THE_LOYAL',
    'DISCOUNT_FOR_DISLOYAL'
);
CREATE TYPE subscription_status AS ENUM (
    'ACTIVE',
    'PAUSED',
    'COMPLETED'
);
CREATE TYPE messagetype AS ENUM ('EMAIL', 'PUSH', 'SMS');

CREATE TABLE subscriptions (
    id bigserial PRIMARY KEY,
    scenario_name scenario_name NOT NULL,
    biz_id bigint NOT NULL,
    status subscription_status NOT NULL,
    coupon_id bigint,
    created_at timestamptz NOT NULL DEFAULT NOW(),
    CONSTRAINT biz_id_and_scenario_name UNIQUE (biz_id, scenario_name)
);

CREATE TABLE subscription_versions (
    id bigserial PRIMARY KEY,
    subscription_id bigint NOT NULL REFERENCES subscriptions(id),
    coupon_id bigint,
    created_at timestamptz NOT NULL DEFAULT NOW(),
    status subscription_status
);

CREATE TABLE messages (
    id bigserial PRIMARY KEY,
    time_to_send timestamptz NOT NULL DEFAULT NOW(),
    message_anchor text NOT NULL,
    message_type messagetype NOT NULL,
    message_meta jsonb NOT NULL CHECK ( jsonb_typeof(message_meta) = 'object' ),
    doorman_ids bigint[] NOT NULL,
    promoter_ids bigint[] NOT NULL,
    scenario_names scenario_name[] NOT NULL,
    created_at timestamptz NOT NULL DEFAULT NOW(),
    processed_at timestamptz,
    error varchar(1024),
    processed_meta jsonb
);
CREATE INDEX messages_message_type_unprocessed_btree_idx
ON messages
USING btree (message_type)
WHERE processed_at IS NULL;

CREATE TABLE certificate_mailing_stats (
    id bigserial PRIMARY KEY,
    biz_id bigint NOT NULL,
    coupon_id bigint NOT NULL,
    scenario_name scenario_name NOT NULL,
    sent bigint NOT NULL,
    clicked bigint NOT NULL,
    opened bigint NOT NULL,
    sent_date varchar(10) NOT NULL,
    created_at timestamptz NOT NULL DEFAULT NOW()
);
CREATE INDEX certificate_mailing_stats_biz_id_coupon_id_btree
ON certificate_mailing_stats
USING btree (biz_id, coupon_id);
