-- 039: Device tokens for push notification channels
-- Stores device push tokens per user, supporting multiple channels:
-- FCM (Google), APNs (Apple), HMS (Huawei), XIAOMI, OPPO, VIVO

CREATE TABLE device_tokens (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL,
    platform VARCHAR(20) NOT NULL CHECK (platform IN ('ANDROID','IOS')),
    channel VARCHAR(20) NOT NULL CHECK (channel IN ('FCM','APNS','HMS','XIAOMI','OPPO','VIVO')),
    token TEXT NOT NULL,
    device_id VARCHAR(200),
    device_model VARCHAR(200),
    app_version VARCHAR(50),
    is_active BOOLEAN NOT NULL DEFAULT true,
    last_used_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE UNIQUE INDEX idx_device_tokens_token ON device_tokens(token);
CREATE INDEX idx_device_tokens_user_active ON device_tokens(user_id, is_active);

-- Add PROMOTION type to announcements for advertisement / promotional push
ALTER TABLE announcements DROP CONSTRAINT IF EXISTS announcements_type_check;
ALTER TABLE announcements ADD CONSTRAINT announcements_type_check
    CHECK (type IN ('SYSTEM','ACTIVITY','REWARD','UPGRADE','ANNOUNCEMENT','PROMOTION'));
