CREATE TABLE IF NOT EXISTS ratings (
    id BIGSERIAL PRIMARY KEY,
    user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    target_type VARCHAR(20) NOT NULL, -- 'app', 'course', 'sub_course'
    target_id BIGINT NOT NULL DEFAULT 0, -- 0 for app rating, course_id or sub_course_id otherwise
    stars SMALLINT NOT NULL CHECK (stars >= 1 AND stars <= 5),
    review TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (user_id, target_type, target_id)
);

CREATE INDEX idx_ratings_target ON ratings (target_type, target_id);
CREATE INDEX idx_ratings_user ON ratings (user_id);
