<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Auth;

class ExpertCertificate extends Model
{
    protected $guarded = ['id', 'created_at', 'updated_at'];

    protected $casts = [
        'verified' => 'boolean',
        'verified_at' => 'datetime',
    ];

    protected static function booted(): void
    {
        static::saving(function (ExpertCertificate $cert): void {
            if ($cert->verified && ! $cert->verified_at) {
                $cert->verified_at = now();
                $cert->verified_by = Auth::id();
            }
            if (! $cert->verified) {
                $cert->verified_at = null;
                $cert->verified_by = null;
            }
        });
    }

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

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