<?php

namespace App\Http\Controllers\admin;

use App\Constants\HttpStatus;
use App\Http\Controllers\Controller;
use App\Services\RoomService;
use App\Services\SecretService;
use App\Services\TopUpService;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Services\UserService;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use App\Services\AddressService;

use Illuminate\Http\JsonResponse;
use App\Models\User as UserModel;

class User extends Controller
{


    /**
     * @api {get} /admin/user 会员列表
     * @apiGroup 会员管理
     *
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiParam {int} [page=1]
     * @apiParam {int} [limit=10]
     * @apiParam {string} [first_name] 用户昵称
     * @apiParam {string} [member_id] 房主 tg会员ID
     * @apiParam {string} [game_id] 游戏ID
     *
     * @apiSuccess (data) {Object} data
     * @apiSuccess (data) {int} data.total 数量
     * @apiSuccess (data) {Object[]} data.data 列表
     * @apiSuccess (data) {int} data.data.id
     * @apiSuccess (data) {int} data.data.member_id tg会员id
     * @apiSuccess (data) {string} data.data.first_name 昵称
     * @apiSuccess (data) {string} data.data.usdt 用户usdt钱包地址
     * @apiSuccess (data) {string} data.data.game_id 游戏ID
     * @apiSuccess (data) {string} data.data.updated_at
     * @apiSuccess (data) {string} data.data.created_at
     * @apiSuccess (data) {string} data.data.secret_key 找回账号的秘钥
     */
    public function index(): JsonResponse
    {
        try {
            request()->validate([
                'game_id' => ['nullable', 'string', 'min:1'],
                'member_id' => ['nullable', 'string', 'min:1'],
                'first_name' => ['nullable', 'string', 'min:1'],
                'username' => ['nullable', 'string', 'min:1'],
            ]);
            $search = request()->all();
            $result = UserService::paginate($search);
        } catch (ValidationException $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error(intval($e->getCode()));
        }
        return $this->success($result);
    }


    /**
     * @api {post} /admin/user/merge 账户合并
     * @apiGroup 会员管理
     * @apiDescription 合并后，余额，银行卡，USDT地址 将合并到新用户，请谨慎操作
     *
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiParam {string} member_id 接收者的member_id
     * @apiParam {string} secret_key 被合并的用户的秘钥
     */
    public function merge(): JsonResponse
    {
        DB::beginTransaction();
        try {
            $params = request()->validate([
                'member_id' => ['required', 'string', 'min:1'],
                'secret_key' => ['required', 'string', 'min:1'],
            ]);

            $res = SecretService::migration($params['member_id'], $params['secret_key']);
            if (!$res) {
                throw new Exception(lang("迁移失败"), HttpStatus::CUSTOM_ERROR);
            }
            $oldUser = UserModel::where('secret_key', $params['secret_key'])->first();
            $newUser = UserModel::where('member_id', $params['member_id'])->first();
            App::setLocale($oldUser->language);
            $text = lang('账户转移通知') . "：\n";
            $text .= lang('管理员已将您的账户转移至新用户') . "\n\n";
            $text .= lang('新用户信息') . "\n";
            $text .= lang('用户ID') . "：{$newUser->getMemberId()}\n";
            if ($newUser->getUsername()) {
                $text .= lang("用户名") . "：@{$newUser->getUsername()}\n";
            }
            $text .= lang('昵称') . "：{$newUser->getFirstName()}\n";
            TopUpService::notifyTransferSuccess($oldUser->getMemberId(), $text);
            App::setLocale($newUser->language);
            $text = lang("账户转移通知") . "：\n";
            $text .= lang("管理员已将指定账户转移至您的账户") . "\n\n";
            $text .= lang('原账户信息') . "\n\n";
            $text .= lang('用户ID') . "：{$oldUser->getMemberId()}\n";
            if ($oldUser->getUsername()) {
                $text .= lang('用户名') . "：@{$oldUser->getUsername()}\n";
            }
            $text .= lang('昵称') . "：{$oldUser->getFirstName()}\n";
            TopUpService::notifyTransferSuccess($newUser->getMemberId(), $text);
            DB::commit();
        } catch (ValidationException $e) {
            DB::rollBack();
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            DB::rollBack();
            if ($e->getCode() == HttpStatus::CUSTOM_ERROR) {
                return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
            }
            return $this->error(intval($e->getCode()));
        }
        return $this->success(msg: '已完成迁移');
    }


    public function address()
    {
        try {
            request()->validate([
                'member_id' => ['required', 'integer', 'min:1'],
            ]);
            $search = request()->all();
            $result = AddressService::findAll($search);
        } catch (ValidationException $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error(intval($e->getCode()));
        }
        return $this->success($result);
    }

}
