<?php

namespace App\Observers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Arr;

use App\Models\Room;
use App\Models\RoomStatusLog;

class RoomObserver
{
    /**
     * Handle the Room "created" event.
     */
    public function created(Room $room): void
    {
        // 建立初始 log
        $this->createStatusLog($room);
    }

    /**
     * Handle the Room "updated" event.
     */
    public function updated(Room $room): void
    {
        // 檢查是否有變更狀態
        if ($room->wasChanged()) {
            $this->createStatusLog($room);
        }
        if ($room->isDirty('status')) {
            $now = now();

            // 找到最後一筆未結束 session
            $lastSession = $room->sessions()->whereNull('ended_at')->latest('started_at')->first();

            if ($lastSession) {
                // 結束上一筆 session
                $lastSession->update([
                    'status' => $room->status->value,
                    'ended_at' => $now,
                ]);
            }

            // 如果狀態是 active 或 maintain，開新 session
            if (in_array($room->status->value, ['active', 'maintain'])) {
                $mode = $room->status->value === 'active' ? 'normal' : 'test';
                $room->sessions()->create([
                    'mode' => $mode,
                    'status' => $room->status->value,
                    'started_at' => $now,
                ]);
            }
        }
    }

    /**
     * Handle the Room "deleted" event.
     */
    public function deleted(Room $room): void
    {
        $message = sprintf(
            "%s:%s%s (%s:%s) 已刪除",
            $room->branch->name,
            $room->type->value,
            $room->name,
            $room->internal_ip,
            $room->port
        );
        $this->createStatusLog($room,$message);
    }
    
    /**
     * 建立 RoomStatusLog
     */
    private function createStatusLog(Room $room,$log_message =null): void
    {
        $message=($log_message !=null)?$log_message:$room->log_message ?? '';
        RoomStatusLog::create([
            'branch_id'  => $room->branch->id,
            'room_id'    => $room->id,
            'user_id'    => Auth::id() ?? 0,
            'is_online'  => $room->is_online,
            'status'     => $room->status,
            'started_at' => $room->started_at,
            'ended_at'   => $room->ended_at,
            'message'    => $message,
            'source'     => $this->getSource($room),
        ]);
    }

    private function getSource(Room $room): string
    {
        return app()->runningInConsole() ? 'system' : ($room->log_source ?? 'manual');
    }
}
