<?php

namespace App\Models;

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

class WebauthnCredential extends Model
{
    protected $guarded = [];

    protected $casts = [
        'transports' => 'array',
        'sign_count' => 'integer',
        'last_used_at' => 'datetime',
    ];

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

    protected static function booted(): void
    {
        // The unique index is on a fixed-length hash, since credential_id can exceed the
        // index key-length limit. Derive it automatically from credential_id.
        static::saving(function (self $cred): void {
            $cred->credential_id_hash = hash('sha256', (string) $cred->credential_id);
        });
    }
}
