<?php


namespace App\Http\Controllers\V1;


use App\Enums\ApiEnum;
use App\Services\Api\FriendService;
use App\Services\Base\ErrorCode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use PHPUnit\Util\Exception;

class FriendController extends Controller
{
    //好友相关操作
    private $friendService;

    public function __construct()
    {
        parent::__construct();
        $this->friendService = new FriendService();
    }

    /**
     * 好友列表
     */
    public function friendsList(){
        $data = $this->friendService->friendsList();
        return $this->success($data);
    }

    /**
     * 好友操作  拉黑、删除、取消拉黑
     */
    public function friendAction(Request $request){
        try {
            $user = auth('api')->user();
            $lock = Cache::lock(ApiEnum::FRIEND_ACTION.$user->id, 1);
            if ($lock->get()) {
                DB::beginTransaction();
                $this->friendService->friendAction($user,$request->id,$request->type);
                DB::commit();
                $lock->release();
            }else{
                throw new Exception(trans('api.REQUESTS_TOO_OFTEN'));
            }
        }catch (\Exception $exception){
            DB::rollBack();
            return $this->error($exception->getMessage());
        }
        return $this->success();
    }

    /**
     * 搜索所有用户
     */
    public function searchUser(Request $request){
        try {
            $data = $this->friendService->searchUser($request);
        }catch (\Exception $exception){
            return $this->error($exception->getMessage());
        }
        return $this->success($data);
    }


    /**
     * 申请添加好友
     */
    public function applyFriend(Request $request){
        try {
            $user = auth('api')->user();
            $lock = Cache::lock(ApiEnum::FRIEND_ACTION.$user->id, 1);
            if ($lock->get()) {
                DB::beginTransaction();
                $this->friendService->applyFriend($user,$request);
                DB::commit();
                $lock->release();
            }else{
                throw new Exception(trans('api.REQUESTS_TOO_OFTEN'));
            }
        }catch (\Exception $exception){
            DB::rollBack();
            return $this->error($exception->getMessage());
        }
        return $this->success();
    }

    /**
     * 同意好友申请
     */
    public function friendPass(Request $request){
        try {
            DB::beginTransaction();
            $this->friendService->friend_pass($request->id);
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            return $this->error($exception->getMessage());
        }
        return $this->success();
    }


}
