<?php

namespace app\common\model;

use app\common\service\GameHotDataCoordinator;
use support\think\Model;

/**
 * 用户主表
 */
class User extends Model
{
    protected $name = 'user';

    protected $autoWriteTimestamp = true;

    /**
     * 生成 10 位唯一对外标识（大写字母与数字，排除易混淆字符）
     */
    public static function generateUniquePublicCode10(): string
    {
        $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
        $len = strlen($chars);
        for ($attempt = 0; $attempt < 80; $attempt++) {
            $code = '';
            for ($i = 0; $i < 10; $i++) {
                $code .= $chars[random_int(0, $len - 1)];
            }
            if (!self::where('uuid', $code)->find()) {
                return $code;
            }
        }
        throw new \RuntimeException('Failed to generate unique user uuid');
    }

    public static function formatLoginRemark(int $timestamp, string $ip): string
    {
        return '最后登录：' . date('Y-m-d H:i:s', $timestamp) . ' IP:' . $ip;
    }

    protected $type = [
        'create_time' => 'integer',
        'update_time' => 'integer',
        'coin' => 'string',
        'total_deposit_coin' => 'string',
        'total_withdraw_coin' => 'string',
        'bet_flow_coin' => 'string',
        'risk_flags' => 'integer',
        'current_streak' => 'integer',
    ];

    public function channel(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(Channel::class, 'channel_id', 'id');
    }

    public function admin(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\Admin::class, 'admin_id', 'id');
    }

    public function resetPassword(int|string $uid, string $newPassword): int
    {
        return $this->where(['id' => $uid])->update(['password' => hash_password($newPassword)]);
    }

    public static function onAfterWrite(User $model): void
    {
        $id = filter_var($model->getAttr('id'), FILTER_VALIDATE_INT);
        if ($id !== false && $id > 0) {
            GameHotDataCoordinator::afterUserCommitted($id);
        }
    }

    public static function onAfterDelete(User $model): void
    {
        $id = filter_var($model->getAttr('id'), FILTER_VALIDATE_INT);
        if ($id !== false && $id > 0) {
            GameHotDataCoordinator::afterUserCommitted($id);
        }
    }
}
