<?php

namespace App\Models;

use App\Enums\Gender;
use App\Enums\Status;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    protected function serializeDate(DateTimeInterface $date): string
    {
        return $date->format('Y-m-d H:i:s');
    }

    protected $table = 'users';

    public const CREATED_AT = 'create_time';

    public const UPDATED_AT = 'update_time';

    protected $fillable = [
        'username',
        'email',
        'phone',
        'password',
        'nickname',
        'avatar',
        'gender',
        'birthday',
        'signature',
        'group_id',
        'usercenter_master_id',
        'status',
        'email_verified_at',
        'phone_verified_at',
        'last_login_at',
        'last_login_ip',
        'login_count',
    ];

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

    protected $casts = [
        'status' => Status::class,
        'gender' => Gender::class,
        'email_verified_at' => 'datetime',
        'phone_verified_at' => 'datetime',
        'last_login_at' => 'datetime',
        'birthday' => 'date',
    ];

    public function group(): BelongsTo
    {
        return $this->belongsTo(UserGroup::class, 'group_id');
    }

    public function thirdPartyBindings(): HasMany
    {
        return $this->hasMany(UserThirdParty::class, 'user_id');
    }

    /**
     * 扩展数据（动态字段值）
     */
    public function extData(): HasMany
    {
        return $this->hasMany(UserExtData::class, 'user_id');
    }

    public function isEmailVerified(): bool
    {
        return $this->email_verified_at !== null;
    }

    public function isPhoneVerified(): bool
    {
        return $this->phone_verified_at !== null;
    }

    public function incrementLoginCount(string $ip): void
    {
        $this->increment('login_count');
        $this->update([
            'last_login_at' => now(),
            'last_login_ip' => $ip,
        ]);
    }

    public function scopeEnabled(Builder $query): Builder
    {
        return $query->where('status', Status::ENABLED);
    }
}
