ALTER TABLE users
  ADD COLUMN invite_code VARCHAR(16) NULL,
  ADD COLUMN first_paid_at DATETIME(6) NULL,
  ADD UNIQUE KEY ux_users_invite_code (invite_code);

CREATE TABLE referrals (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  inviter_id BIGINT UNSIGNED NOT NULL,
  invitee_id BIGINT UNSIGNED NOT NULL UNIQUE,
  device_uuid VARCHAR(64) NULL,
  status ENUM('bound','reg_rewarded','paid_rewarded','rejected') NOT NULL DEFAULT 'bound',
  reg_rewarded_at DATETIME(6) NULL,
  paid_rewarded_at DATETIME(6) NULL,
  created_at DATETIME(6) NOT NULL,
  INDEX ix_referrals_inviter (inviter_id, created_at),
  FOREIGN KEY (inviter_id) REFERENCES users(id),
  FOREIGN KEY (invitee_id) REFERENCES users(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE reward_claims (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id BIGINT UNSIGNED NOT NULL,
  task_key VARCHAR(32) NOT NULL,
  external_ref VARCHAR(64) NOT NULL DEFAULT '',
  granted_days INT NOT NULL,
  granted_at DATETIME(6) NOT NULL,
  UNIQUE KEY ux_claim_user_task (user_id, task_key),
  UNIQUE KEY ux_claim_task_ref (task_key, external_ref),
  FOREIGN KEY (user_id) REFERENCES users(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

ALTER TABLE subscriptions MODIFY source ENUM('trial','code','pay','invite','task') NOT NULL;
