<?php

namespace App\Support;

use App\Models\Room;
use Illuminate\Http\Request;

class EventsRegistrationSession
{
    private static function key(Room $room): string
    {
        return "meet.events.registration.{$room->uuid}";
    }

    /** @return array{email: ?string, name: ?string, badge_code: ?string, speaker_token: ?string}|null */
    public static function get(Request $request, Room $room): ?array
    {
        $data = $request->session()->get(self::key($room));

        return is_array($data) ? $data : null;
    }

    public static function isVerified(Request $request, Room $room): bool
    {
        $data = self::get($request, $room);

        return filled($data['badge_code'] ?? null) && filled($data['email'] ?? null);
    }

    public static function isSpeakerVerified(Request $request, Room $room): bool
    {
        $data = self::get($request, $room);

        return filled($data['speaker_token'] ?? null) && filled($data['email'] ?? null);
    }

    public static function canJoinEventsLinked(Request $request, Room $room): bool
    {
        return self::isVerified($request, $room) || self::isSpeakerVerified($request, $room);
    }

    /** @param  array{email?: ?string, name?: ?string, badge_code?: ?string, speaker_token?: ?string}  $data */
    public static function store(Request $request, Room $room, array $data): void
    {
        $existing = self::get($request, $room) ?? [];

        $request->session()->put(self::key($room), [
            'email' => array_key_exists('email', $data) ? $data['email'] : ($existing['email'] ?? null),
            'name' => array_key_exists('name', $data) ? $data['name'] : ($existing['name'] ?? null),
            'badge_code' => array_key_exists('badge_code', $data) ? $data['badge_code'] : ($existing['badge_code'] ?? null),
            'speaker_token' => array_key_exists('speaker_token', $data) ? $data['speaker_token'] : ($existing['speaker_token'] ?? null),
        ]);
    }

    public static function forget(Request $request, Room $room): void
    {
        $request->session()->forget(self::key($room));
    }
}
