<?php

namespace App\Models;

use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Tournament extends Model
{
    use HasFactory, SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'user_id',
        'club_id',
        'name',
        'description',
        'picture',
        'start_date',
        'end_date',
        'start_time',
        'end_time',
        'status',
        'link'
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'start_date' => 'date',
        'end_date' => 'date',
        'start_time' => 'datetime',
        'end_time' => 'datetime',
    ];

    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        static::creating(function ($model) {
            $model->user_id = auth()->id();
            $model->slug = Str::slug($model->name);
        });

        static::updating(function ($model) {
            $model->user_id = auth()->id();
            $model->slug = Str::slug($model->name);
        });
    }

    /**
     * Get the event's picture
     *
     * @return Attribute
     */
    protected function picture(): Attribute
    {
        return new Attribute(
            get: fn ($value) => $value !== null ? env('UPLOAD_URL') . $value : env('UPLOAD_URL').'/tournaments/placeholder.jpg',
        );
    }

    /**
     * Get the user that owns the event.
     *
     * @return BelongsTo
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get the club that owns the event.
     *
     * @return BelongsTo
     */
    public function club(): BelongsTo
    {
        return $this->belongsTo(Club::class);
    }

    /**
     * The users that belong to the tournaments.
     *
     * @return HasMany
     */
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'tournament_users', 'tournament_id', 'user_id');
    }    
}
