<?php

namespace App\Models\Person;

use App\Enums\PersonPhoneType;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Laravel\Scout\Searchable;

class PersonPhone extends Model
{
    /** @use HasFactory<\Database\Factories\Person/PersonPhoneFactory> */
    use HasFactory;

    use Searchable;
    use SoftDeletes;

    protected $fillable = [
        'nu',
        'country_code',
        'type_id',
        'description',
        'person_id',
        'user_id',
        'validated',
        'phone_type',
    ];

    protected $hidden = [
        'user_id',
        'person_id',
        'deleted',
    ];

    public function toSearchableArray(): array
    {
        return [
            'nu' => $this->nu,
        ];
    }

    protected static function booted()
    {
        static::creating(function (PersonPhone $personPhone) {
            if (! isset($personPhone->user_id)) {
                $personPhone->user_id = auth()->id();
            }
        });
    }

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

    public function type(): BelongsTo
    {
        return $this->belongsTo(\App\Models\Person\PhoneType::class, 'type_id');
    }

    protected function casts(): array
    {
        return [
            'validated' => 'boolean',
            'phone_type' => PersonPhoneType::class,
        ];
    }
}
