-- Promotions: each has type, time range, status
CREATE TABLE IF NOT EXISTS promotions (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    type VARCHAR(32) NOT NULL COMMENT 'e.g. NET_WIN',
    start_time TIMESTAMP NOT NULL,
    end_time TIMESTAMP NOT NULL,
    status VARCHAR(20) NOT NULL DEFAULT 'PLANNED' COMMENT 'ACTIVE, INACTIVE, FINISHED, PLANNED',
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY idx_promotions_type_status (type, status),
    KEY idx_promotions_times (start_time, end_time),
    KEY idx_promotions_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Prizes per place for a promotion
CREATE TABLE IF NOT EXISTS promotions_rewards (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    promo_id INT NOT NULL,
    place INT NOT NULL COMMENT '1 = first place, 2 = second, etc.',
    reward BIGINT NOT NULL COMMENT 'Tickets in bigint (1 ticket = 1000000)',
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uk_promotions_rewards_promo_place (promo_id, place),
    KEY idx_promotions_rewards_promo (promo_id),
    CONSTRAINT fk_promotions_rewards_promo FOREIGN KEY (promo_id) REFERENCES promotions(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- User progress per promotion (one row per user per promo)
CREATE TABLE IF NOT EXISTS promotions_users (
    promo_id INT NOT NULL,
    user_id INT NOT NULL,
    points DECIMAL(20,2) NOT NULL DEFAULT 0 COMMENT 'Points as ticket count, 2 decimal places (e.g. 100.25)',
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (promo_id, user_id),
    KEY idx_promotions_users_promo_points (promo_id, points DESC),
    KEY idx_promotions_users_user (user_id),
    CONSTRAINT fk_promotions_users_promo FOREIGN KEY (promo_id) REFERENCES promotions(id) ON DELETE CASCADE,
    CONSTRAINT fk_promotions_users_user FOREIGN KEY (user_id) REFERENCES db_users_a(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
