package models

import (
	"time"

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

// TrackShare représente un lien de partage pour un track
// MIGRATION UUID: Completée. ID et TrackID sont des UUIDs.
type TrackShare struct {
	ID          uuid.UUID      `gorm:"type:uuid;primaryKey" json:"id" db:"id"`
	TrackID     uuid.UUID      `gorm:"type:uuid;not null;index:idx_track_shares_track_id" json:"track_id" db:"track_id"`
	UserID      uuid.UUID      `gorm:"not null;type:uuid;index:idx_track_shares_user_id" json:"user_id" db:"user_id"`
	ShareToken  string         `gorm:"uniqueIndex;not null;size:255" json:"share_token" db:"share_token"`
	Permissions string         `gorm:"type:varchar(50);default:'read'" json:"permissions" db:"permissions"` // "read", "download", "read,download"
	ExpiresAt   *time.Time     `json:"expires_at,omitempty" db:"expires_at"`
	AccessCount int64          `gorm:"default:0" json:"access_count" db:"access_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 `gorm:"index" json:"-" db:"deleted_at"`

	// Relations
	Track *Track `gorm:"foreignKey:TrackID;constraint:OnDelete:CASCADE" json:"track,omitempty"`
	User  *User  `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE" json:"user,omitempty"`
}

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

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