package models

import (
	"time"

	"github.com/google/uuid"
	"gorm.io/gorm"
)

// Playlist représente une playlist de tracks
// MIGRATION UUID: Completée. ID et UserID sont des UUIDs.
type Playlist struct {
	ID            uuid.UUID      `gorm:"type:uuid;primaryKey" json:"id" db:"id"`
	UserID        uuid.UUID      `gorm:"type:uuid;not null" json:"user_id" db:"user_id"`
	Title         string         `gorm:"column:name;not null;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"`
	TrackCount    int            `gorm:"default:0" json:"track_count" db:"track_count"`
	FollowerCount int            `gorm:"default:0" json:"follower_count" db:"follower_count"`
	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 `json:"-" db:"deleted_at"`

	// Relations
	User          User                   `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE" json:"-"`
	Tracks        []PlaylistTrack        `gorm:"foreignKey:PlaylistID;constraint:OnDelete:CASCADE" json:"tracks,omitempty"`
	Collaborators []PlaylistCollaborator `gorm:"foreignKey:PlaylistID;constraint:OnDelete:CASCADE" json:"collaborators,omitempty"`
}

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

// PlaylistTrack représente l'association entre une playlist et un track avec position
type PlaylistTrack struct {
	ID         uuid.UUID `gorm:"type:uuid;primaryKey" json:"id" db:"id"`
	PlaylistID uuid.UUID `gorm:"type:uuid;not null" json:"playlist_id" db:"playlist_id"`
	TrackID    uuid.UUID `gorm:"type:uuid;not null" json:"track_id" db:"track_id"`
	Position   int       `gorm:"not null" json:"position" db:"position"`
	AddedBy    uuid.UUID `gorm:"type:uuid;not null" json:"added_by" db:"added_by"`
	AddedAt    time.Time `gorm:"autoCreateTime" json:"added_at" db:"added_at"`

	// Relations
	Playlist Playlist `gorm:"foreignKey:PlaylistID;constraint:OnDelete:CASCADE" json:"-"`
	Track    Track    `gorm:"foreignKey:TrackID;constraint:OnDelete:CASCADE" json:"track,omitempty"`
}

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

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

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