package models

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

	"github.com/google/uuid" // Import uuid
)

// PlaylistVersionAction représente le type d'action effectuée sur une playlist
type PlaylistVersionAction string

const (
	PlaylistVersionActionCreated  PlaylistVersionAction = "created"
	PlaylistVersionActionUpdated  PlaylistVersionAction = "updated"
	PlaylistVersionActionRestored PlaylistVersionAction = "restored"
)

// PlaylistVersion représente une version d'une playlist
// T0509: Create Playlist Version History
// MIGRATION UUID: Completée. ID et PlaylistID sont des UUIDs.
type PlaylistVersion struct {
	ID          uuid.UUID             `gorm:"type:uuid;primaryKey" json:"id" db:"id"`
	PlaylistID  uuid.UUID             `gorm:"type:uuid;not null;index:idx_playlist_versions_playlist_id" json:"playlist_id" db:"playlist_id"`
	UserID      uuid.UUID             `gorm:"type:uuid;not null;index:idx_playlist_versions_user_id" json:"user_id" db:"user_id"`
	Version     int                   `gorm:"not null" json:"version" db:"version"`
	Action      PlaylistVersionAction `gorm:"not null;size:50;index:idx_playlist_versions_action" json:"action" db:"action"`
	Title       string                `gorm:"size:200" json:"title" db:"title"`
	Description string                `gorm:"type:text" json:"description,omitempty" db:"description"`
	IsPublic    bool                  `gorm:"default:true" json:"is_public" db:"is_public"`
	CoverURL    string                `gorm:"size:500" json:"cover_url,omitempty" db:"cover_url"`
	// Snapshot des tracks au moment de la version (JSON)
	TracksSnapshot string    `gorm:"type:text" json:"tracks_snapshot,omitempty" db:"tracks_snapshot"`
	CreatedAt      time.Time `gorm:"autoCreateTime;index:idx_playlist_versions_created_at" json:"created_at" db:"created_at"`
	UpdatedAt      time.Time `gorm:"autoUpdateTime" json:"updated_at" db:"updated_at"`

	// Relations
	Playlist *Playlist `gorm:"foreignKey:PlaylistID;constraint:OnDelete:CASCADE" json:"playlist,omitempty"`
	User     *User     `gorm:"foreignKey:UserID;constraint:OnDelete:SET NULL" json:"user,omitempty"`
}

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

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