<?php

namespace App\Models;

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

class LinkCode extends Model
{
    protected $fillable = ['user_id', 'code', 'expires_at'];

    protected function casts(): array
    {
        return [
            'expires_at' => 'datetime',
        ];
    }

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

    public static function generateFor(User $user): self
    {
        static::query()->where('user_id', $user->id)->delete();

        return static::create([
            'user_id' => $user->id,
            'code' => strtoupper(Str::random(8)),
            'expires_at' => now()->addMinutes(10),
        ]);
    }
}
