<?php

namespace App\Http\Controllers;

use App\Http\Requests\SendRoomSwitchCommandRequest;
use App\Http\Requests\ReceiveSwitchRequest;
use App\Services\TcpSocketClient;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use App\Models\Branch;
use App\Models\Room;
use App\Enums\RoomStatus;
use App\Http\Responses\ApiResponse;

use Illuminate\Support\Facades\Log;
/**
 * @OA\Tag(
 *     name="Auth",
 *     description="包廂控制"
 * )
 */
class RoomControlController extends Controller
{
    /**
     * @OA\Post(
     *     path="/api/room/sendSwitch",
     *     summary="送出包廂控制指令",
     *     description="依據傳入的 room_id 與 command，透過 TCP 傳送對應指令給包廂電腦。",
     *     operationId="sendRoomSwitchCommand",
     *     tags={"Room Control"},
     *     security={{"Authorization":{}}},
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(ref="#/components/schemas/SendRoomSwitchCommandRequest")
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功傳送指令並回傳 TCP 回應",
     *         @OA\JsonContent(
     *             allOf={
     *                 @OA\Schema(ref="#/components/schemas/ApiResponse"),
     *                 @OA\Schema(
     *                     @OA\Property(property="data", ref="#/components/schemas/Room")
     *                 )
     *             }
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="Unauthorized",
     *         @OA\JsonContent(
     *             allOf={
     *                 @OA\Schema(ref="#/components/schemas/ApiResponse"),
     *                 @OA\Schema(
     *                     @OA\Property(property="code", type="string", example="UNAUTHORIZED"),
     *                     @OA\Property(property="message", type="string", example="Unauthorized"),
     *                     @OA\Property(property="data", type="null")
     *                 )
     *             }
     *         )
     *     ),
     *     @OA\Parameter(
     *         name="Accept",
     *         in="header",
     *         required=true,
     *         @OA\Schema(type="string", default="application/json")
     *     )
     * )
     */
    public function sendSwitch(SendRoomSwitchCommandRequest $request): JsonResponse
    {
        $validated = $request->validated();
        $branch = Branch::where('name',$validated['branch_name'])->first();

        if (!$branch) {
            return ApiResponse::error('分店不存在');
        }
        
        if (empty($branch->external_ip) ) {
            return ApiResponse::error('分店未設定 外部URL');
        }

        $command = $validated['command'];
        $payload = [
            'branch_name'  => $validated['branch_name'],
            'room_name'  => $validated['room_name'],
            'command'    => $command,
            'started_at' => $validated['started_at'] ?? null,
            'ended_at'   => $validated['ended_at'] ?? null,
        ];
        $user = \App\Models\User::find(2);
        $token = $user->api_plain_token;
        $api = new \App\Services\ApiClient($branch->external_ip,$token);
        $response = $api->post('/api/room/sendSwitch', $payload);

        if (!$response->successful()) {
            return ApiResponse::error('指令發送失敗：' . $response->body());
        }

        return ApiResponse::success("命令已發送：$command");
    }
    public function receiveSwitch(ReceiveSwitchRequest $request): JsonResponse
    {
        $validated = $request->validated();

        if ($validated['status'] === 'error') {
            $validated['started_at'] = null;
            $validated['ended_at'] = null;
        }

        $room = Room::updateOrCreate(
            ['id' => $validated['id']], 
            [
                'branch_id' => $validated['branch_id'],
                'type'      => $validated['type'],
                'name'      => $validated['name'],
                'floor'       => $validated['floor'],
                //'internal_ip' => $validated['internal_ip'],
                //'port'        => $validated['port'],
                'is_online'   => $validated['is_online'],
                'status'      => $validated['status'],
                'started_at'  => $validated['started_at'],
                'ended_at'    => $validated['ended_at'],
            ]
        );
        return ApiResponse::success($room->refresh());
    }
}
