<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Photobooth\PhotoboothConnectRedeemRequest;
use App\Models\Event;
use App\Services\Photobooth\PhotoboothConnectCodeService;
use Illuminate\Http\JsonResponse;

class PhotoboothConnectController extends Controller
{
    public function __construct(private readonly PhotoboothConnectCodeService $service) {}

    public function store(PhotoboothConnectRedeemRequest $request): JsonResponse
    {
        $record = $this->service->redeem($request->input('code'));

        if (! $record) {
            return response()->json([
                'message' => __('Ungültiger oder abgelaufener Verbindungscode.'),
            ], 422);
        }

        $record->loadMissing('event.photoboothSetting');
        $event = $record->event;
        $setting = $event?->photoboothSetting;

        if (! $event || ! $setting || ! $setting->enabled || $setting->mode !== 'sparkbooth') {
            return response()->json([
                'message' => __('Photobooth ist nicht im Sparkbooth-Modus aktiv.'),
            ], 409);
        }

        return response()->json([
            'data' => [
                'event_name' => $this->resolveEventName($event),
                'upload_url' => route('api.v1.photobooth.upload'),
                'username' => $setting->username,
                'password' => $setting->password,
                'expires_at' => optional($setting->expires_at)->toIso8601String(),
                'response_format' => ($setting->metadata ?? [])['sparkbooth_response_format']
                    ?? config('photobooth.sparkbooth.response_format', 'json'),
            ],
        ]);
    }

    private function resolveEventName(?Event $event): ?string
    {
        if (! $event) {
            return null;
        }

        $name = $event->name;

        if (is_string($name) && trim($name) !== '') {
            return $name;
        }

        if (is_array($name)) {
            foreach ($name as $value) {
                if (is_string($value) && trim($value) !== '') {
                    return $value;
                }
            }
        }

        return $event->slug ?: null;
    }
}
