package models

import (
	"gorm.io/gorm"
	"time"

	"github.com/google/uuid"
)

// PlaybackAnalytics représente les analytics de lecture d'un track
// T0356: Create Playback Analytics Database Model
// MIGRATION UUID: UserID et TrackID migrés vers UUID pour cohérence
type PlaybackAnalytics struct {
	ID             uuid.UUID  `gorm:"type:uuid;primaryKey" json:"id"`
	TrackID        uuid.UUID  `gorm:"type:uuid;not null;index:idx_playback_analytics_track_id" json:"track_id"`
	Track          Track      `gorm:"foreignKey:TrackID;constraint:OnDelete:CASCADE" json:"track,omitempty"`
	UserID         uuid.UUID  `gorm:"type:uuid;not null;index:idx_playback_analytics_user_id" json:"user_id"`
	User           User       `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE" json:"user,omitempty"`
	PlayTime       int        `gorm:"not null;default:0" json:"play_time"` // seconds
	PauseCount     int        `gorm:"not null;default:0" json:"pause_count"`
	SeekCount      int        `gorm:"not null;default:0" json:"seek_count"`
	CompletionRate float64    `gorm:"type:decimal(5,2);not null;default:0" json:"completion_rate"` // percentage (0-100)
	StartedAt      time.Time  `gorm:"not null" json:"started_at"`
	EndedAt        *time.Time `json:"ended_at,omitempty"`
	CreatedAt      time.Time  `gorm:"autoCreateTime;index:idx_playback_analytics_created_at" json:"created_at"`
	UpdatedAt      time.Time  `gorm:"autoUpdateTime" json:"updated_at"`
}

// TableName définit le nom de la table pour GORM
func (PlaybackAnalytics) TableName() string {
	return "playback_analytics"
}

// BeforeCreate hook GORM pour générer UUID si non défini
func (m *PlaybackAnalytics) BeforeCreate(tx *gorm.DB) error {
	if m.ID == uuid.Nil {
		m.ID = uuid.New()
	}
	return nil
}
