<?php

namespace App\Models;

use App\Helpers\PasswordHelper;
use App\Mail\PasswordResetEmail;
use App\Mail\RegistrationEmail;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

final class User extends Authenticatable
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use CanResetPassword, HasFactory, Notifiable;

    protected $primaryKey = 'ID';

    public $timestamps = false;

    protected $fillable = [
        'name',
        'truename',
        'email',
        'role',
        'gold',
        'qq',
        'mobilenumber',
        'passwd',
        'creatime',
        'photo',
        'is_activated',
        'activation_token',
        'activation_sent_at',
        'google_id',
        'password_setup_token',
        'password_setup_expires_at',
    ];

    protected $hidden = [
        'passwd',
        'remember_token',
        'activation_token',
        'password_setup_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'is_activated' => 'boolean',
            'activation_sent_at' => 'datetime',
            'password_setup_expires_at' => 'datetime',
        ];
    }

    public function checkPassword($password)
    {
        return PasswordHelper::verifyPassword($this->name, $password, $this->passwd);
    }

    public function getAuthPassword()
    {
        return $this->passwd;
    }

    public function sendPasswordResetNotification($token)
    {
        try {
            Mail::to($this->email)->send(new PasswordResetEmail($this, $token));
        } catch (\Exception $e) {
            Log::error('Failed to send password reset email: '.$e->getMessage());
            $this->notify(new \App\Notifications\ResetPasswordNotification($token));
        }
    }

    public function sendRegistrationEmail($password = null)
    {
        try {
            Mail::to($this->email)->send(new RegistrationEmail($this));
        } catch (\Exception $e) {
            Log::error('Failed to send registration email: '.$e->getMessage());
        }
    }
}
