-- Add unique constraint for upsert on artist_earnings
DO $$ 
BEGIN
  -- Check if the constraint already exists
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint 
    WHERE conname = 'artist_earnings_artist_track_period_unique'
  ) THEN
    -- Add unique constraint for upsert operations
    ALTER TABLE artist_earnings 
    ADD CONSTRAINT artist_earnings_artist_track_period_unique 
    UNIQUE (artist_id, track_id, period_start);
  END IF;
END $$;

-- Add unique constraint for stream_counts if not exists
DO $$ 
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint 
    WHERE conname = 'stream_counts_track_date_unique'
  ) THEN
    ALTER TABLE stream_counts 
    ADD CONSTRAINT stream_counts_track_date_unique 
    UNIQUE (track_id, date);
  END IF;
END $$;

-- Create index for faster listening history queries
CREATE INDEX IF NOT EXISTS idx_listening_history_track_played 
ON listening_history(track_id, played_at DESC);

-- Create index for artist earnings queries
CREATE INDEX IF NOT EXISTS idx_artist_earnings_artist_period 
ON artist_earnings(artist_id, period_start DESC);
