-- 2026_06_22_012_activity_messages.sql
BEGIN;

CREATE TABLE IF NOT EXISTS public.activity_messages (
    id              BIGSERIAL PRIMARY KEY,
    activity_id     BIGINT       NOT NULL,
    user_id         BIGINT       NOT NULL,
    star_id         BIGINT       NOT NULL,
    nickname        VARCHAR(50),                            -- 缓存昵称（写入时回查，避免读时 RPC 反查）
    avatar_url      VARCHAR(500),                           -- 缓存头像 URL
    content         VARCHAR(500) NOT NULL,
    status          SMALLINT     NOT NULL DEFAULT 0,
    created_at      BIGINT       NOT NULL,
    updated_at      BIGINT       NOT NULL,
    deleted_at      TIMESTAMP WITH TIME ZONE,                              -- gorm.DeletedAt 软删除时间戳
    CONSTRAINT fk_messages_activity
        FOREIGN KEY (activity_id) REFERENCES public.activities(id) ON DELETE CASCADE,
    CONSTRAINT fk_messages_user
        FOREIGN KEY (user_id)     REFERENCES public.users(id),
    CONSTRAINT fk_messages_star
        FOREIGN KEY (star_id)     REFERENCES public.stars(star_id),
    CONSTRAINT chk_activity_messages_status CHECK (status BETWEEN 0 AND 2)
);

ALTER SEQUENCE activity_messages_id_seq RESTART WITH 10000;

CREATE INDEX IF NOT EXISTS idx_activity_messages_activity_created
    ON public.activity_messages (activity_id, created_at DESC, id DESC)
    WHERE deleted_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_activity_messages_user_created
    ON public.activity_messages (user_id, created_at DESC)
    WHERE deleted_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_activity_messages_activity_incr
    ON public.activity_messages (activity_id, id DESC)
    WHERE deleted_at IS NULL;

COMMENT ON TABLE  public.activity_messages                       IS '活动留言表';
COMMENT ON COLUMN public.activity_messages.id                   IS '主键，自增';
COMMENT ON COLUMN public.activity_messages.activity_id           IS 'FK -> activities.id';
COMMENT ON COLUMN public.activity_messages.user_id               IS '留言用户 ID';
COMMENT ON COLUMN public.activity_messages.star_id               IS '所属明星/星球 ID';
COMMENT ON COLUMN public.activity_messages.nickname              IS '缓存昵称（写入时回查，避免读时 RPC 反查）';
COMMENT ON COLUMN public.activity_messages.avatar_url            IS '缓存头像 URL';
COMMENT ON COLUMN public.activity_messages.content               IS '留言正文，1-500 字';
COMMENT ON COLUMN public.activity_messages.status                IS '0=正常|1=隐藏|2=已删除';
COMMENT ON COLUMN public.activity_messages.created_at            IS '留言时间，毫秒时间戳';
COMMENT ON COLUMN public.activity_messages.updated_at            IS '更新时间，毫秒时间戳';
COMMENT ON COLUMN public.activity_messages.deleted_at            IS '软删除时间戳（gorm.DeletedAt，NULL=未删除）';

COMMIT;
