<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

class UserTrustLink extends Model
{
    protected $fillable = [
        'user_id',
        'trust_service_id',
        'status',
        'remote_id',
        'remote_user_url',
        'remote_proof_url',
        'note',
        'challenge_code',
        'challenge_sent_at',
        'challenge_expires_at',
        'challenge_verified_at',
        'verified_by',
        'verified_at',
    ];

    protected $casts = [
        'challenge_sent_at' => 'datetime',
        'challenge_expires_at' => 'datetime',
        'challenge_verified_at' => 'datetime',
        'verified_at' => 'datetime',
    ];

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

    public function service(): BelongsTo
    {
        return $this->belongsTo(TrustService::class, 'trust_service_id');
    }

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

    public function isExpired(): bool
    {
        return $this->challenge_expires_at && now()->isAfter($this->challenge_expires_at);
    }

    public function generateChallenge(): void
    {
        $this->update([
            'challenge_code' => strtoupper(Str::random(10)),
            'challenge_sent_at' => now(),
            'challenge_expires_at' => now()->addDays(7),
            'status' => 'challenge_sent',
        ]);
    }
}
