BEGIN;

-- Version dependency checks
DO $$
  ASSERT current_module_version('PROFILES') = 1, 'Dependency version mismatch: PROFILES';
  ASSERT current_module_version('EVENT_TRACKER') = 2, 'Dependency version mismatch: EVENT_TRACKER';
$$ LANGUAGE plpgsql;

-- Plugin version history
INSERT INTO version_history (component, from_version, to_version, author) VALUES ('REWARDCAMPAIGN', 0, 1, 'Initial Creation');


CREATE TABLE campaigns(
  campaign_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  communityid INTEGER NOT NULL REFERENCES communities(communityid) ON DELETE CASCADE ON UPDATE CASCADE,
  target_rewards INTEGER,
  campaign_name TEXT NOT NULL,
  moderator_role_id BIGINT,
  logging_webhook_url TEXT,
  started_at TIMESTAMPTZ,
  completed_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  _timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE UNIQUE INDEX campaigns_communities_names ON campaigns(communityid, LOWER(campaign_name));

CREATE TABLE campaign_rewards_earned(
  earned_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  campaign_id INTEGER NOT NULL REFERENCES campaigns ON DELETE CASCADE ON UPDATE CASCADE,
  profileid INTEGER NOT NULL REFERENCES user_profiles(profileid) ON DELETE CASCADE ON UPDATE CASCADE,
  event_id INTEGER REFERENCES events ON DELETE SET NULL ON UPDATE CASCADE,
  twitch_user_id TEXT,
  twitch_user_name TEXT,
  fulfilled_at TIMESTAMPTZ,
  fulfilled_note TEXT,
  modnote TEXT,
  reference TEXT,
  logged_messageid BIGINT,
  earned_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  earned_reason TEXT NOT NULL,
  _timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- TODO: Possibly reference table for form destination?

COMMIT;
