-- Migration: Create playlist_follows table
-- T0489: Create Playlist Follow Feature

-- Create playlist_follows table
CREATE TABLE IF NOT EXISTS playlist_follows (
    id BIGSERIAL PRIMARY KEY,
    playlist_id BIGINT NOT NULL,
    user_id BIGINT NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP,
    
    -- Foreign keys
    CONSTRAINT fk_playlist_follows_playlist
        FOREIGN KEY (playlist_id)
        REFERENCES playlists(id)
        ON DELETE CASCADE,
    
    CONSTRAINT fk_playlist_follows_user
        FOREIGN KEY (user_id)
        REFERENCES users(id)
        ON DELETE CASCADE,
    
    -- Unique constraint: un utilisateur ne peut suivre une playlist qu'une fois
    CONSTRAINT uq_playlist_follows_playlist_user
        UNIQUE (playlist_id, user_id)
);

-- Create indexes
CREATE INDEX IF NOT EXISTS idx_playlist_follows_playlist_id 
    ON playlist_follows(playlist_id) 
    WHERE deleted_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_playlist_follows_user_id 
    ON playlist_follows(user_id) 
    WHERE deleted_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_playlist_follows_deleted_at 
    ON playlist_follows(deleted_at);

-- Add comment
COMMENT ON TABLE playlist_follows IS 'Table des follows de playlists par les utilisateurs';

-- Add follower_count column to playlists table if it doesn't exist
DO $$ 
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns 
        WHERE table_name = 'playlists' AND column_name = 'follower_count'
    ) THEN
        ALTER TABLE playlists ADD COLUMN follower_count INTEGER DEFAULT 0;
        CREATE INDEX IF NOT EXISTS idx_playlists_follower_count ON playlists(follower_count);
    END IF;
END $$;

