package models

import (
	"github.com/google/uuid"
	"time"

	"gorm.io/gorm"
)

// TrackPlay représente une lecture de track pour analytics
// MIGRATION UUID: Completée. ID, TrackID et UserID sont des UUIDs.
type TrackPlay struct {
	ID        uuid.UUID      `gorm:"type:uuid;primaryKey" json:"id" db:"id"`
	TrackID   uuid.UUID      `gorm:"type:uuid;not null;index:idx_track_plays_track_id" json:"track_id" db:"track_id"`
	UserID    *uuid.UUID     `gorm:"type:uuid;index:idx_track_plays_user_id" json:"user_id,omitempty" db:"user_id"`
	Duration  int            `gorm:"not null" json:"duration" db:"duration"` // seconds played
	PlayedAt  time.Time      `gorm:"not null;index:idx_track_plays_played_at" json:"played_at" db:"played_at"`
	Device    string         `gorm:"size:100" json:"device,omitempty" db:"device"`
	IPAddress string         `gorm:"size:45" json:"ip_address,omitempty" db:"ip_address"`
	CreatedAt time.Time      `gorm:"autoCreateTime" json:"created_at" db:"created_at"`
	UpdatedAt time.Time      `gorm:"autoUpdateTime" json:"updated_at" db:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"-" db:"deleted_at"`

	// Relations
	Track Track `gorm:"foreignKey:TrackID;constraint:OnDelete:CASCADE" json:"-"`
	User  *User `gorm:"foreignKey:UserID;constraint:OnDelete:SET NULL" json:"-"`
}

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

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