<?php

namespace App\Services\Meet;

use App\Models\Room;
use App\Models\Session;
use App\Models\Whiteboard;

class WhiteboardService
{
    public function ensureForSession(Session $session, string $template = 'blank'): Whiteboard
    {
        return Whiteboard::firstOrCreate(
            ['session_id' => $session->id],
            [
                'owner_ref' => $session->owner_ref,
                'room_id' => $session->room_id,
                'template' => $template,
                'state' => $this->templateState($template),
            ],
        );
    }

    public function ensureForRoom(Room $room, string $template = 'blank'): Whiteboard
    {
        return Whiteboard::firstOrCreate(
            ['room_id' => $room->id, 'session_id' => null],
            [
                'owner_ref' => $room->owner_ref,
                'template' => $template,
                'state' => $this->templateState($template),
            ],
        );
    }

    /**
     * @param  array<string, mixed>  $state
     */
    public function saveState(Whiteboard $whiteboard, array $state): Whiteboard
    {
        $whiteboard->update(['state' => $state]);

        return $whiteboard->fresh();
    }

    /**
     * @return array<string, mixed>
     */
    protected function templateState(string $template): array
    {
        return match ($template) {
            'grid' => ['template' => 'grid', 'strokes' => [], 'objects' => [], 'background' => '#f8fafc'],
            'retrospective' => [
                'template' => 'retrospective',
                'strokes' => [],
                'objects' => [
                    ['type' => 'column', 'label' => 'Went well', 'x' => 40, 'y' => 40],
                    ['type' => 'column', 'label' => 'To improve', 'x' => 340, 'y' => 40],
                    ['type' => 'column', 'label' => 'Actions', 'x' => 640, 'y' => 40],
                ],
                'background' => '#ffffff',
            ],
            default => ['template' => 'blank', 'strokes' => [], 'objects' => [], 'background' => '#ffffff'],
        };
    }
}
