<?php

declare(strict_types=1);

namespace ImovelZapAi\Signatures\Infrastructure\Persistence\Eloquent;

use Database\Factories\SignerFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use ImovelZapAi\Conversations\Infrastructure\Persistence\Eloquent\ContactModel;
use ImovelZapAi\Shared\Infrastructure\Persistence\Concerns\BelongsToTenant;
use ImovelZapAi\Shared\Infrastructure\Persistence\Concerns\HasUuidPrimaryKey;
use ImovelZapAi\Signatures\Domain\Enums\SignerRole;
use ImovelZapAi\Signatures\Domain\Enums\SignerStatus;

class SignerModel extends Model
{
    use BelongsToTenant;
    use HasFactory;
    use HasUuidPrimaryKey;

    protected $table = 'signature_signers';

    protected $fillable = [
        'tenant_id', 'signature_request_id', 'contact_id', 'name', 'email', 'phone',
        'role', 'order', 'status', 'access_token_hash', 'access_token_prefix',
        'signed_at', 'rejected_at', 'viewed_at', 'otp_hash', 'otp_expires_at',
        'otp_attempts', 'typed_name',
    ];

    protected function casts(): array
    {
        return [
            'role' => SignerRole::class,
            'status' => SignerStatus::class,
            'order' => 'integer',
            'otp_attempts' => 'integer',
            'signed_at' => 'datetime',
            'rejected_at' => 'datetime',
            'viewed_at' => 'datetime',
            'otp_expires_at' => 'datetime',
        ];
    }

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

    public function request(): BelongsTo
    {
        return $this->belongsTo(SignatureRequestModel::class, 'signature_request_id');
    }

    public function contact(): BelongsTo
    {
        return $this->belongsTo(ContactModel::class, 'contact_id');
    }

    public function evidences(): HasMany
    {
        return $this->hasMany(SignatureEvidenceModel::class, 'signer_id');
    }

    public function reminders(): HasMany
    {
        return $this->hasMany(SignatureReminderModel::class, 'signer_id');
    }
}
