<?php

namespace App\Http\Controllers\Api\Tenant;

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

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

    public function store(PhotoboothConnectCodeStoreRequest $request, Event $event): JsonResponse
    {
        $this->assertEventBelongsToTenant($request, $event);

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

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

        $expiresInMinutes = $request->input('expires_in_minutes');
        $result = $this->service->create($event, $expiresInMinutes ? (int) $expiresInMinutes : null);

        return response()->json([
            'data' => [
                'code' => $result['code'],
                'expires_at' => $result['expires_at']->toIso8601String(),
            ],
        ]);
    }

    protected function assertEventBelongsToTenant(PhotoboothConnectCodeStoreRequest $request, Event $event): void
    {
        $tenantId = (int) $request->attributes->get('tenant_id');

        if ($tenantId !== (int) $event->tenant_id) {
            abort(403, 'Event gehört nicht zu diesem Tenant.');
        }
    }
}
