<?php

namespace App\Http\Controllers\Goodnight;

use App\Http\Resources\Goodnight\RoomCollection;
use App\Http\Resources\Goodnight\RoomMemberCollection;
use App\Http\Resources\Goodnight\RoomMessageCollection;
use App\Http\Resources\Goodnight\RoomResource;
use App\Models\User\UserModel;
use App\Models\Goodnight\EnterModel;
use App\Models\Goodnight\RoomMemberModel;
use App\Models\Goodnight\RoomMessageModel;
use App\Services\Goodnight\NoticeService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Miniprogram\Auth;
use App\Models\Goodnight\RoomModel;

class RoomController extends Controller
{
    //

    public function index(Request $request)
    {
        $uid = Auth::auth();
        $builder = RoomModel::whereHas('members', function ($query) use ($uid) {
            return $query->where('uid', $uid);
        });
        $rooms = $builder->orderBy('updated_at', 'desc')->paginate($request->get('per_page', 20));
        foreach ($rooms as $room) {
            $room->lastMessage;
            $room->unread_cnt = RoomMessageModel::where('room_id', $room->id)->where(
                'uid',
                '<>',
                $uid
            )->where('read_at', 0)->count();
            foreach ($room->members as $member) {
                $member->user_info = UserModel::select('nickname', 'headimgurl', 'sex')->find($member->uid);
            }
        }
        return new RoomCollection($rooms);
    }


    public function show(Request $request, int $id)
    {
        $uid = Auth::auth();
        $room = RoomModel::findOrFail($id);
        foreach ($room->members as $member) {
            $member->user_info = UserModel::select('nickname', 'headimgurl', 'sex')->find($member->uid);
            $member->enter = EnterModel::where('uid', $member->uid)->where('room_id', $id)->first();
        }
        $room->unread_cnt = RoomMessageModel::where('room_id', $room->id)->where('uid', '<>', $uid)->where(
            'read_at',
            0
        )->count();
        $room->lastMessage;
        $room->activity;
        return new RoomResource($room);
    }


    public function messages(Request $request, $id)
    {
        $uid = Auth::auth();
        $room = RoomModel::findOrFail($id);
        $builder = RoomMessageModel::where('room_id', $id);
        $messages = $builder->orderBy('id', 'desc')->paginate($request->get('per_page', 20));
        $builder->where('read_at', 0)->where('uid', '<>', $uid)->update(['read_at' => time()]);
        return new RoomMessageCollection($messages);
    }


    public function members(Request $request, $id)
    {
        $room = RoomModel::findOrFail($id);
        $members = RoomMemberModel::where('room_id', $id)->orderBy('id', 'desc')->get();
        foreach ($members as $member) {
            $member->user_info = UserModel::select('nickname', 'headimgurl', 'sex')->find($member->uid);
        }
        return new RoomMemberCollection($members);
    }


    public function createMessage(Request $request, $id)
    {
        $this->validate($request, [
            'content' => 'required',
        ]);
        $type = $request->input('type', 'text');
        $uid = Auth::auth();
        $room = RoomModel::findOrFail($id);
        $message = RoomMessageModel::create([
            'uid' => $uid,
            'type' => $type,
            'content' => $request->input('content'),
            'room_id' => $id,
        ]);
        $room->update(['interacted_at' => time()]);

        try {
            $to_uid = RoomMemberModel::where('uid', '<>', $uid)->where('room_id', $room->id)->value('uid');
            $ns = new NoticeService();
            $ns->receiveRoomComment($to_uid, $uid);
        } catch (\Exception $e) {
            app('sentry')->captureException($e);
        }
        return response()->json([
            'code' => 200,
            'message' => 'OK',
            'data' => $message
        ]);
    }


    public function createTask(Request $request, $id)
    {
        $uid = Auth::auth();
        $roomMember = RoomMemberModel::where('uid', $uid)->where('room_id', $id)->firstOrFail();
        $roomMember->update($request->all());
        return response()->json([
            'code' => 200,
            'message' => 'OK',
        ]);
    }


    public function partners(Request $request)
    {
        $uid = Auth::auth();
        $builder = RoomMemberModel::whereIn(
            'room_id',
            RoomModel::whereHas('members', function ($query) use ($uid) {
                $query->where('uid', $uid);
            })->orderBy('updated_at', 'desc')->pluck('id')
        )->where('uid', '<>', $uid);
        $total = $builder->count();
        $members = $builder->orderBy('id', 'desc')->limit(4)->get();
        foreach ($members as $member) {
            $member->user_info = UserModel::select('nickname', 'headimgurl', 'sex')->find($member->uid);
        }
        return response()->json([
            'code' => 200,
            'message' => 'OK',
            'data' => $members,
            'meta' => [
                'total' => $total,
            ]
        ]);
    }
}
