package models

import (
	"time"

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

// PlaylistPermission représente les permissions possibles pour un collaborateur
type PlaylistPermission string

const (
	// PlaylistPermissionRead permet de lire la playlist
	PlaylistPermissionRead PlaylistPermission = "read"
	// PlaylistPermissionWrite permet de modifier la playlist (ajouter/retirer des tracks)
	PlaylistPermissionWrite PlaylistPermission = "write"
	// PlaylistPermissionAdmin permet toutes les actions, y compris la gestion des collaborateurs
	PlaylistPermissionAdmin PlaylistPermission = "admin"
)

// IsValid vérifie si la permission est valide
func (p PlaylistPermission) IsValid() bool {
	return p == PlaylistPermissionRead || p == PlaylistPermissionWrite || p == PlaylistPermissionAdmin
}

// String retourne la représentation string de la permission
func (p PlaylistPermission) String() string {
	return string(p)
}

// PlaylistCollaborator représente un collaborateur d'une playlist avec ses permissions
// MIGRATION UUID: Completée. ID et PlaylistID sont des UUIDs.
type PlaylistCollaborator struct {
	ID         uuid.UUID          `gorm:"type:uuid;primaryKey" json:"id" db:"id"`
	PlaylistID uuid.UUID          `gorm:"type:uuid;not null;index:idx_playlist_collaborators_playlist_id" json:"playlist_id" db:"playlist_id"`
	UserID     uuid.UUID          `gorm:"not null;type:uuid;index:idx_playlist_collaborators_user_id" json:"user_id" db:"user_id"`
	Permission PlaylistPermission `gorm:"not null;type:varchar(20);default:'read'" json:"permission" db:"permission"`
	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
	Playlist Playlist `gorm:"foreignKey:PlaylistID;constraint:OnDelete:CASCADE" json:"-"`
	User     User     `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE" json:"user,omitempty"`
}

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

// CanRead vérifie si le collaborateur peut lire la playlist
func (pc *PlaylistCollaborator) CanRead() bool {
	return pc.Permission == PlaylistPermissionRead ||
		pc.Permission == PlaylistPermissionWrite ||
		pc.Permission == PlaylistPermissionAdmin
}

// CanWrite vérifie si le collaborateur peut modifier la playlist
func (pc *PlaylistCollaborator) CanWrite() bool {
	return pc.Permission == PlaylistPermissionWrite ||
		pc.Permission == PlaylistPermissionAdmin
}

// CanAdmin vérifie si le collaborateur peut administrer la playlist
func (pc *PlaylistCollaborator) CanAdmin() bool {
	return pc.Permission == PlaylistPermissionAdmin
}

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