-- Migration: Create track_plays table for playback analytics
-- T0291: Create Track Playback Analytics Database Model

CREATE TABLE track_plays (
    id BIGSERIAL PRIMARY KEY,
    track_id BIGINT NOT NULL REFERENCES tracks(id) ON DELETE CASCADE,
    user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
    duration INTEGER NOT NULL,
    played_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    device VARCHAR(100),
    ip_address VARCHAR(45),
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP
);

-- Indexes for performance
CREATE INDEX idx_track_plays_track_id ON track_plays(track_id);
CREATE INDEX idx_track_plays_user_id ON track_plays(user_id);
CREATE INDEX idx_track_plays_played_at ON track_plays(played_at DESC);
CREATE INDEX idx_track_plays_track_played ON track_plays(track_id, played_at DESC);

-- Index for soft deletes
CREATE INDEX idx_track_plays_deleted_at ON track_plays(deleted_at);

