-- +goose Up
-- +goose StatementBegin

CREATE TABLE billing.subscriptions (
    subscription_id       UUID PRIMARY KEY DEFAULT uuidv7(),
    billing_account_id    UUID NOT NULL REFERENCES billing.accounts(billing_account_id),
    status                TEXT NOT NULL DEFAULT 'active',
    current_period_start  TIMESTAMPTZ,
    current_period_end    TIMESTAMPTZ,
    cancel_at_period_end  BOOLEAN NOT NULL DEFAULT FALSE,
    canceled_at           TIMESTAMPTZ,
    ended_at              TIMESTAMPTZ,
    created_at            TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at            TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_subscriptions_billing_account_id ON billing.subscriptions(billing_account_id);
CREATE INDEX idx_subscriptions_status ON billing.subscriptions(status);

CREATE TRIGGER trigger_subscriptions_updated_at
    BEFORE UPDATE ON billing.subscriptions
    FOR EACH ROW
    EXECUTE FUNCTION update_updated_at_column();

-- Per-schema role grants (Decision 115).
GRANT ALL ON ALL TABLES IN SCHEMA billing TO billing_owner;
GRANT ALL ON ALL TABLES IN SCHEMA billing TO billing_writer;
GRANT SELECT ON ALL TABLES IN SCHEMA billing TO billing_reader;

-- +goose StatementEnd

-- +goose Down
-- +goose StatementBegin
DROP TRIGGER IF EXISTS trigger_subscriptions_updated_at ON billing.subscriptions;
DROP INDEX IF EXISTS billing.idx_subscriptions_status;
DROP INDEX IF EXISTS billing.idx_subscriptions_billing_account_id;
DROP TABLE IF EXISTS billing.subscriptions;

-- +goose StatementEnd
