<?php

namespace App\Domain\Identity\Models;

use App\Domain\Participant\Models\Participant;
use App\Domain\Shared\Traits\Auditable;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PortalInvitation extends Model
{
    use HasUuid, BelongsToAcademy, Auditable;

    protected $fillable = [
        'academy_id',
        'person_id',
        'participant_id',
        'token_hash',
        'channel',
        'sent_to',
        'expires_at',
        'consumed_at',
        'consumed_by',
        'revoked_at',
        'created_by',
        'created_ip',
    ];

    /**
     * The raw token is never an attribute — only its hash is stored. It is
     * returned once, from PortalInvitationService::issue(), and after that the
     * only copy is in the link the member was sent.
     */
    protected $hidden = ['token_hash'];

    protected function casts(): array
    {
        return [
            'expires_at' => 'datetime',
            'consumed_at' => 'datetime',
            'revoked_at' => 'datetime',
        ];
    }

    public function person(): BelongsTo
    {
        return $this->belongsTo(Person::class);
    }

    public function participant(): BelongsTo
    {
        return $this->belongsTo(Participant::class);
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function isLive(): bool
    {
        return $this->consumed_at === null
            && $this->revoked_at === null
            && $this->expires_at->isFuture();
    }

    public function statusLabel(): string
    {
        return match (true) {
            $this->consumed_at !== null => 'مُفعّلة',
            $this->revoked_at !== null => 'ملغاة',
            $this->expires_at->isPast() => 'منتهية',
            default => 'في الانتظار',
        };
    }
}
