-- 044_playlist_share_links.sql
-- Playlist Share Links (BE-DB-005: Create migration for playlist_share_link table)
-- Add table for shareable playlist links with expiration

-- === PLAYLIST SHARE LINKS ===
CREATE TABLE IF NOT EXISTS public.playlist_share_links (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    playlist_id UUID NOT NULL REFERENCES public.playlists(id) ON DELETE CASCADE,
    user_id UUID NOT NULL REFERENCES public.users(id) ON DELETE CASCADE,
    
    -- Share Info
    share_token VARCHAR(255) NOT NULL,
    expires_at TIMESTAMPTZ,
    access_count BIGINT NOT NULL DEFAULT 0,
    
    -- Timestamps
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    deleted_at TIMESTAMPTZ,
    
    CONSTRAINT uq_playlist_share_links_token UNIQUE (share_token)
);

-- Indexes
CREATE INDEX IF NOT EXISTS idx_playlist_share_links_playlist_id ON public.playlist_share_links(playlist_id);
CREATE INDEX IF NOT EXISTS idx_playlist_share_links_user_id ON public.playlist_share_links(user_id);
CREATE INDEX IF NOT EXISTS idx_playlist_share_links_share_token ON public.playlist_share_links(share_token);
CREATE INDEX IF NOT EXISTS idx_playlist_share_links_expires_at ON public.playlist_share_links(expires_at) WHERE expires_at IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_playlist_share_links_deleted_at ON public.playlist_share_links(deleted_at) WHERE deleted_at IS NULL;

-- Comments
COMMENT ON TABLE public.playlist_share_links IS 'Shareable public links for playlists with optional expiration';
COMMENT ON COLUMN public.playlist_share_links.share_token IS 'Unique token for the share link';
COMMENT ON COLUMN public.playlist_share_links.expires_at IS 'Optional expiration date for the share link';
COMMENT ON COLUMN public.playlist_share_links.access_count IS 'Number of times the share link has been accessed';

