<?php

declare(strict_types=1);

namespace App\Models;

use App\Support\LegacyPassword;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    /** @use HasFactory<UserFactory> */
    use HasFactory, HasRoles, Notifiable;

    protected $fillable = [
        'name',
        'username',
        'email',
        'password',
        'password_legacy',
        'url',
        'login_count',
        'login_ip',
        'login_at',
        'reg_ip',
        'last_post_at',
    ];

    protected $hidden = [
        'password',
        'password_legacy',
        'remember_token',
    ];

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'login_count' => 'integer',
            'login_at' => 'datetime',
            'last_post_at' => 'datetime',
        ];
    }

    public function articles(): HasMany
    {
        return $this->hasMany(Article::class);
    }

    public function attemptLegacyPasswordUpgrade(string $plainPassword): bool
    {
        if (blank($this->password_legacy)) {
            return false;
        }

        if (! LegacyPassword::verify($plainPassword, $this->password_legacy)) {
            return false;
        }

        $this->forceFill([
            'password' => Hash::make($plainPassword),
            'password_legacy' => null,
        ])->save();

        return true;
    }

    public function hasLegacyPassword(): bool
    {
        return filled($this->password_legacy);
    }
}
