<?php

declare(strict_types=1);

namespace ImovelZapAi\Organizations\Infrastructure\Persistence\Eloquent;

use Database\Factories\OrganizationInvitationFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use ImovelZapAi\Authentication\Domain\Enums\SystemRole;
use ImovelZapAi\Organizations\Domain\Enums\InvitationStatus;
use ImovelZapAi\Shared\Infrastructure\Persistence\Concerns\HasUuidPrimaryKey;
use ImovelZapAi\Tenancy\Infrastructure\Persistence\Eloquent\TenantModel;
use ImovelZapAi\Users\Infrastructure\Persistence\Eloquent\UserModel;

class OrganizationInvitationModel extends Model
{
    /** @use HasFactory<OrganizationInvitationFactory> */
    use HasFactory;
    use HasUuidPrimaryKey;

    protected $table = 'organization_invitations';

    /** @var list<string> */
    protected $fillable = [
        'tenant_id',
        'email',
        'role',
        'token',
        'status',
        'invited_by_user_id',
        'expires_at',
        'accepted_at',
    ];

    /** @return array<string, string> */
    protected function casts(): array
    {
        return [
            'role' => SystemRole::class,
            'status' => InvitationStatus::class,
            'expires_at' => 'datetime',
            'accepted_at' => 'datetime',
        ];
    }

    public function tenant(): BelongsTo
    {
        return $this->belongsTo(TenantModel::class, 'tenant_id');
    }

    public function invitedBy(): BelongsTo
    {
        return $this->belongsTo(UserModel::class, 'invited_by_user_id');
    }

    public function isPending(): bool
    {
        return $this->status === InvitationStatus::Pending
            && $this->expires_at !== null
            && $this->expires_at->isFuture();
    }

    protected static function newFactory(): OrganizationInvitationFactory
    {
        return OrganizationInvitationFactory::new();
    }
}
