<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

class FolderInvitation extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'folder_id',
        'token',
        'email',
        'expires_at',
        'used_at',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'expires_at' => 'datetime',
            'used_at' => 'datetime',
        ];
    }

    /**
     * Boot the model.
     */
    protected static function boot(): void
    {
        parent::boot();

        static::creating(function (FolderInvitation $invitation) {
            if (empty($invitation->token)) {
                $invitation->token = Str::uuid()->toString();
            }
        });
    }

    /**
     * Get the folder that owns the invitation.
     *
     * @return BelongsTo<Folder, $this>
     */
    public function folder(): BelongsTo
    {
        return $this->belongsTo(Folder::class);
    }

    /**
     * Check if the invitation is valid (not expired, not used).
     */
    public function isValid(): bool
    {
        if ($this->used_at !== null) {
            return false;
        }

        return $this->expires_at->isFuture();
    }
}
