-- 042_media_processing.sql
-- Media Processing, Transcoding and HLS (Legacy/Lab aligned with Origin where applicable)
-- Note: Origin doesn't fully specify these in the main doc excerpt, assuming Lab Schema is authoritative for these specific tables.

-- === HLS STREAMS ===
CREATE TABLE public.hls_streams (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    track_id UUID NOT NULL REFERENCES public.tracks(id) ON DELETE CASCADE,
    
    playlist_url VARCHAR(500) NOT NULL,
    segments_count INTEGER DEFAULT 0 NOT NULL,
    bitrates JSONB DEFAULT '[]'::jsonb NOT NULL,
    status VARCHAR(20) DEFAULT 'pending' NOT NULL,
    
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_hls_streams_track_id ON public.hls_streams(track_id);
CREATE INDEX idx_hls_streams_status ON public.hls_streams(status);

-- === HLS TRANSCODE QUEUE ===
CREATE TABLE public.hls_transcode_queue (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    track_id UUID NOT NULL REFERENCES public.tracks(id) ON DELETE CASCADE,
    
    priority INTEGER DEFAULT 5 NOT NULL,
    status VARCHAR(20) DEFAULT 'pending' NOT NULL,
    retry_count INTEGER DEFAULT 0 NOT NULL,
    max_retries INTEGER DEFAULT 3 NOT NULL,
    error_message TEXT,
    
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    started_at TIMESTAMPTZ,
    completed_at TIMESTAMPTZ
);

CREATE INDEX idx_hls_transcode_queue_status_priority ON public.hls_transcode_queue(status, priority DESC);
CREATE INDEX idx_hls_transcode_queue_track_id ON public.hls_transcode_queue(track_id);

-- === BITRATE ADAPTATION LOGS ===
CREATE TABLE public.bitrate_adaptation_logs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    track_id UUID NOT NULL REFERENCES public.tracks(id) ON DELETE CASCADE,
    user_id UUID NOT NULL REFERENCES public.users(id) ON DELETE CASCADE,
    
    old_bitrate INTEGER NOT NULL,
    new_bitrate INTEGER NOT NULL,
    reason VARCHAR(50) NOT NULL,
    network_bandwidth INTEGER,
    
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_bitrate_adaptation_logs_track_id ON public.bitrate_adaptation_logs(track_id);
CREATE INDEX idx_bitrate_adaptation_logs_created_at ON public.bitrate_adaptation_logs(created_at);