<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
class TgGroupUsers extends Model
{
    protected $table = 'tg_group_users';

    protected $guarded = ['id'];

    // 时间字段类型自动转为 Carbon 实例
    protected $casts = [
        'raw_data' => 'array',
    ];

    // Telegram status 常量定义
    public const STATUS_CREATOR = 'creator';             // 群主
    public const STATUS_ADMINISTRATOR = 'administrator'; // 管理员
    public const STATUS_MEMBER = 'member';               // 普通成员
    public const STATUS_RESTRICTED = 'restricted';       // 被限制的成员
    public const STATUS_LEFT = 'left';                   // 已离开
    public const STATUS_KICKED = 'kicked';               // 被踢出

    // 可选：提供一个状态中文对照表（静态方法）
    public static function statusLabel(string $status): string
    {
        return match ($status) {
            self::STATUS_CREATOR       => '群主',
            self::STATUS_ADMINISTRATOR => '管理员',
            self::STATUS_MEMBER        => '成员',
            self::STATUS_RESTRICTED    => '受限成员',
            self::STATUS_LEFT          => '已离开',
            self::STATUS_KICKED        => '被踢出',
            default                    => '未知',
        };
    }

    public static function updateOrCreateFromTelegram(array $chatMemberData, int|string $chatId): self
    {
        // 改进的安全判断方式
        if (
            !isset($chatMemberData['user']) ||
            !is_array($chatMemberData['user']) ||
            !isset($chatMemberData['user']['id']) ||
            !isset($chatMemberData['status'])
        ) {
            throw new \InvalidArgumentException('无效的 Telegram ChatMember 数据结构');
        }

        $user = $chatMemberData['user'];

        return self::updateOrCreate(
            [
                'chat_id' => $chatId,
                'user_id' => $user['id'],
            ],
            [
                'first_name'     => $user['first_name'] ?? null,
                'last_name'      => $user['last_name'] ?? null,
                'username'       => $user['username'] ?? null,
                'status'         => $chatMemberData['status'],
                'is_bot'         => $user['is_bot'] ?? false,
                'language_code'  => $user['language_code'] ?? null,
                'raw_data'       => json_encode($chatMemberData, JSON_UNESCAPED_UNICODE),
            ]
        );
    }

    public static function GetUsername($username){
        $res=TgGroupUsers::where('username', $username)->first();
        if($res){
            return $res;
        } else {
            return false;
        }
    }
}
