<?php

namespace XZD\AI\V5\Theme;

use XZD\AI\V5\Tools\ToolResult;

/**
 * 主题工具管理器 — 通过适配器执行积分/余额/VIP/封禁/勋章/通知等操作
 */
class ThemeManager
{
    /**
     * 查自己保护 — 管理员可查任何人，普通用户只能查自己
     */
    private static function checkSelfOrAdmin(int $targetUid, int $currentUserId): ?ToolResult
    {
        if ($targetUid <= 0) {
            return ToolResult::error('用户ID无效');
        }
        if ($targetUid === $currentUserId) {
            return null; // 查自己，允许
        }
        if ($currentUserId && current_user_can('manage_options')) {
            return null; // 管理员，允许查任何人
        }
        return ToolResult::error('只能查询自己的数据', 'forbidden');
    }

    /**
     * 获取当前适配器
     */
    private static function adapter(): AdapterInterface
    {
        return AdapterRegistry::getCurrent();
    }

    // 积分系统 (3)

    public static function getPoints(array $params, int $userId): ToolResult
    {
        $uid = $params['user_id'] ?? $userId;
        if (!$uid) return ToolResult::error('用户ID无效');
        $check = self::checkSelfOrAdmin((int) $uid, $userId); if ($check !== null) return $check;
        $points = self::adapter()->getPoints((int) $uid);
        return ToolResult::success(['user_id' => $uid, 'points' => $points]);
    }

    public static function addPoints(array $params, int $userId): ToolResult
    {
        $uid    = (int) ($params['user_id'] ?? 0);
        $amount = (int) ($params['amount'] ?? 0);
        $reason = $params['reason'] ?? '管理员操作';
        if ($uid <= 0) return ToolResult::error('用户ID无效');
        if ($amount <= 0) return ToolResult::error('金额必须大于0');
        $result = self::adapter()->addPoints($uid, $amount, $reason, $userId);
        if ($result['success']) {
            // 触发积分阈值事件
            if (class_exists(\XZD\AI\V5\Tools\EventTrigger::class)) {
                $newPoints = self::adapter()->getPoints($uid);
                \XZD\AI\V5\Tools\EventTrigger::onPointsChanged($uid, $newPoints, 'add');
            }
        }
        return $result['success'] ? ToolResult::success($result, $result['message']) : ToolResult::error($result['message']);
    }

    public static function deductPoints(array $params, int $userId): ToolResult
    {
        $uid    = (int) ($params['user_id'] ?? 0);
        $amount = (int) ($params['amount'] ?? 0);
        $reason = $params['reason'] ?? '管理员操作';
        if ($uid <= 0) return ToolResult::error('用户ID无效');
        if ($amount <= 0) return ToolResult::error('金额必须大于0');
        $result = self::adapter()->deductPoints($uid, $amount, $reason, $userId);
        if ($result['success']) {
            // 触发积分阈值事件
            if (class_exists(\XZD\AI\V5\Tools\EventTrigger::class)) {
                $newPoints = self::adapter()->getPoints($uid);
                \XZD\AI\V5\Tools\EventTrigger::onPointsChanged($uid, $newPoints, 'deduct');
            }
        }
        return $result['success'] ? ToolResult::success($result, $result['message']) : ToolResult::error($result['message']);
    }

    // 余额系统 (3)

    public static function getBalance(array $params, int $userId): ToolResult
    {
        $uid = $params['user_id'] ?? $userId;
        if (!$uid) return ToolResult::error('用户ID无效');
        $check = self::checkSelfOrAdmin((int) $uid, $userId); if ($check !== null) return $check;
        $balance = self::adapter()->getBalance((int) $uid);
        return ToolResult::success(['user_id' => $uid, 'balance' => $balance]);
    }

    public static function addBalance(array $params, int $userId): ToolResult
    {
        $uid    = (int) ($params['user_id'] ?? 0);
        $amount = (float) ($params['amount'] ?? 0);
        $reason = $params['reason'] ?? '管理员操作';
        if ($uid <= 0) return ToolResult::error('用户ID无效');
        if ($amount <= 0) return ToolResult::error('金额必须大于0');
        $result = self::adapter()->addBalance($uid, $amount, $reason, $userId);
        return $result['success'] ? ToolResult::success($result, $result['message']) : ToolResult::error($result['message']);
    }

    public static function deductBalance(array $params, int $userId): ToolResult
    {
        $uid    = (int) ($params['user_id'] ?? 0);
        $amount = (float) ($params['amount'] ?? 0);
        $reason = $params['reason'] ?? '管理员操作';
        if ($uid <= 0) return ToolResult::error('用户ID无效');
        if ($amount <= 0) return ToolResult::error('金额必须大于0');
        $result = self::adapter()->deductBalance($uid, $amount, $reason, $userId);
        return $result['success'] ? ToolResult::success($result, $result['message']) : ToolResult::error($result['message']);
    }

    // VIP系统 (3)

    public static function getVip(array $params, int $userId): ToolResult
    {
        $uid = $params['user_id'] ?? $userId;
        if (!$uid) return ToolResult::error('用户ID无效');
        $check = self::checkSelfOrAdmin((int) $uid, $userId); if ($check !== null) return $check;
        $level = self::adapter()->getVipLevel((int) $uid);
        return ToolResult::success(['user_id' => $uid, 'vip_level' => $level]);
    }

    public static function setVip(array $params, int $userId): ToolResult
    {
        $uid   = (int) ($params['user_id'] ?? 0);
        $level = (int) ($params['level'] ?? 1);
        $days  = (int) ($params['days'] ?? 30);
        if ($uid <= 0) return ToolResult::error('用户ID无效');
        $result = self::adapter()->setVipLevel($uid, $level, $days, $userId);
        return $result['success'] ? ToolResult::success($result, $result['message']) : ToolResult::error($result['message']);
    }

    public static function removeVip(array $params, int $userId): ToolResult
    {
        $uid = (int) ($params['user_id'] ?? 0);
        if ($uid <= 0) return ToolResult::error('用户ID无效');
        $result = self::adapter()->removeVip($uid);
        return $result['success'] ? ToolResult::success($result, $result['message']) : ToolResult::error($result['message']);
    }

    // 封禁/黑名单 (3)

    public static function checkBan(array $params, int $userId): ToolResult
    {
        $uid = $params['user_id'] ?? $userId;
        if (!$uid) return ToolResult::error('用户ID无效');
        $check = self::checkSelfOrAdmin((int) $uid, $userId); if ($check !== null) return $check;
        $banned = self::adapter()->isBanned((int) $uid);
        return ToolResult::success(['user_id' => $uid, 'is_banned' => $banned]);
    }

    public static function banUser(array $params, int $userId): ToolResult
    {
        $uid    = (int) ($params['user_id'] ?? 0);
        $reason = $params['reason'] ?? '违规行为';
        if ($uid <= 0) return ToolResult::error('用户ID无效');
        $result = self::adapter()->banUser($uid, $reason, $userId);
        return $result['success'] ? ToolResult::success($result, $result['message']) : ToolResult::error($result['message']);
    }

    public static function unbanUser(array $params, int $userId): ToolResult
    {
        $uid = (int) ($params['user_id'] ?? 0);
        if ($uid <= 0) return ToolResult::error('用户ID无效');
        $result = self::adapter()->unbanUser($uid, $userId);
        return $result['success'] ? ToolResult::success($result, $result['message']) : ToolResult::error($result['message']);
    }

    // 通知系统 (1)

    public static function sendNotify(array $params, int $userId): ToolResult
    {
        $uid     = (int) ($params['user_id'] ?? 0);
        $title   = $params['title'] ?? '系统通知';
        $content = $params['content'] ?? '';
        if ($uid <= 0) return ToolResult::error('用户ID无效');
        if (empty($content)) return ToolResult::error('通知内容不能为空');
        $result = self::adapter()->sendNotification($uid, $title, $content, $userId);
        return $result['success'] ? ToolResult::success($result, $result['message']) : ToolResult::error($result['message']);
    }

    // 签到系统 (2)

    public static function getCheckin(array $params, int $userId): ToolResult
    {
        $uid = $params['user_id'] ?? $userId;
        if (!$uid) return ToolResult::error('用户ID无效');
        $check = self::checkSelfOrAdmin((int) $uid, $userId); if ($check !== null) return $check;
        $status = self::adapter()->getCheckinStatus((int) $uid);
        return ToolResult::success($status);
    }

    public static function doCheckin(array $params, int $userId): ToolResult
    {
        $uid = (int) ($params['user_id'] ?? $userId);
        if ($uid <= 0) return ToolResult::error('用户ID无效');
        $check = self::checkSelfOrAdmin($uid, $userId); if ($check !== null) return $check;
        $result = self::adapter()->doCheckin($uid);
        return $result['success'] ? ToolResult::success($result, $result['message']) : ToolResult::error($result['message']);
    }

    // 勋章系统 (3)

    public static function getMedals(array $params, int $userId): ToolResult
    {
        $uid = $params['user_id'] ?? $userId;
        if (!$uid) return ToolResult::error('用户ID无效');
        $check = self::checkSelfOrAdmin((int) $uid, $userId); if ($check !== null) return $check;
        $medals = self::adapter()->getMedals((int) $uid);
        return ToolResult::success(['user_id' => $uid, 'medals' => $medals]);
    }

    public static function addMedal(array $params, int $userId): ToolResult
    {
        $uid     = (int) ($params['user_id'] ?? 0);
        $medalId = $params['medal_id'] ?? '';
        if ($uid <= 0) return ToolResult::error('用户ID无效');
        if (empty($medalId)) return ToolResult::error('勋章ID不能为空');
        $result = self::adapter()->addMedal($uid, $medalId);
        return $result['success'] ? ToolResult::success($result, $result['message']) : ToolResult::error($result['message']);
    }

    public static function removeMedal(array $params, int $userId): ToolResult
    {
        $uid     = (int) ($params['user_id'] ?? 0);
        $medalId = $params['medal_id'] ?? '';
        if ($uid <= 0) return ToolResult::error('用户ID无效');
        if (empty($medalId)) return ToolResult::error('勋章ID不能为空');
        $result = self::adapter()->removeMedal($uid, $medalId);
        return $result['success'] ? ToolResult::success($result, $result['message']) : ToolResult::error($result['message']);
    }

    // 订单系统 (1)

    public static function getOrders(array $params, int $userId): ToolResult
    {
        $uid   = $params['user_id'] ?? $userId;
        $limit = (int) ($params['limit'] ?? 20);
        if (!$uid) return ToolResult::error('用户ID无效');
        $check = self::checkSelfOrAdmin((int) $uid, $userId); if ($check !== null) return $check;
        $orders = self::adapter()->getOrders((int) $uid, $limit);
        return ToolResult::success(['user_id' => $uid, 'orders' => $orders, 'count' => count($orders)]);
    }

    // 邀请系统 (1)

    public static function getInvites(array $params, int $userId): ToolResult
    {
        $uid = $params['user_id'] ?? $userId;
        if (!$uid) return ToolResult::error('用户ID无效');
        $check = self::checkSelfOrAdmin((int) $uid, $userId); if ($check !== null) return $check;
        $stats = self::adapter()->getInviteStats((int) $uid);
        return ToolResult::success($stats);
    }

    // 批量通知 (1)

    public static function sendBulkNotify(array $params, int $userId): ToolResult
    {
        $userIds = $params['user_ids'] ?? [];
        $title   = $params['title'] ?? '系统通知';
        $content = $params['content'] ?? '';
        if (empty($userIds)) return ToolResult::error('请指定目标用户ID列表');
        if (empty($content)) return ToolResult::error('通知内容不能为空');
        $result = self::adapter()->sendBulkNotification(array_map('intval', (array)$userIds), $title, $content, $userId);
        return $result['success'] ? ToolResult::success($result, $result['message']) : ToolResult::error($result['message']);
    }

    // Webhook通知 (1)

    public static function sendWebhook(array $params, int $userId): ToolResult
    {
        $url     = $params['webhook_url'] ?? '';
        $title   = $params['title'] ?? 'AI通知';
        $content = $params['content'] ?? '';
        $type    = $params['type'] ?? 'dingtalk';
        if (empty($url)) return ToolResult::error('Webhook URL不能为空');
        if (empty($content)) return ToolResult::error('通知内容不能为空');
        $result = self::adapter()->sendWebhook($url, ['title' => $title, 'content' => $content], $type);
        return $result['success'] ? ToolResult::success($result, $result['message']) : ToolResult::error($result['message']);
    }

    // 论坛增强 (3)

    public static function getForumPlates(array $params, int $userId): ToolResult
    {
        $plates = self::adapter()->getForumPlates();
        return ToolResult::success(['plates' => $plates, 'count' => count($plates)]);
    }

    public static function searchForum(array $params, int $userId): ToolResult
    {
        $keyword = $params['keyword'] ?? '';
        $limit   = min((int)($params['limit'] ?? 20), 50);
        if (empty($keyword)) return ToolResult::error('请输入搜索关键词');
        $topics = self::adapter()->searchForumTopics($keyword, $limit);
        return ToolResult::success(['topics' => $topics, 'count' => count($topics), 'keyword' => $keyword]);
    }

    public static function getForumStats(array $params, int $userId): ToolResult
    {
        $stats = self::adapter()->getForumStats();
        return ToolResult::success($stats);
    }
}
