<?php

namespace App\Http\Controllers\Api\Tenant;

use App\Http\Controllers\Controller;
use App\Http\Requests\Tenant\EventAddonCheckoutRequest;
use App\Http\Requests\Tenant\EventAddonRequest;
use App\Http\Resources\Tenant\EventResource;
use App\Models\Event;
use App\Services\Addons\EventAddonCheckoutService;
use App\Support\ApiError;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Carbon;

class EventAddonController extends Controller
{
    public function __construct(private readonly EventAddonCheckoutService $checkoutService) {}

    public function checkout(EventAddonCheckoutRequest $request, Event $event): JsonResponse
    {
        $tenantId = $request->attributes->get('tenant_id');

        if ($event->tenant_id !== $tenantId) {
            return ApiError::response(
                'event_not_found',
                'Event not accessible',
                __('Das Event konnte nicht gefunden werden.'),
                404,
                ['event_slug' => $event->slug ?? null]
            );
        }

        $eventPackage = $event->eventPackage ?: $event->eventPackages()
            ->orderByDesc('purchased_at')
            ->orderByDesc('created_at')
            ->first();

        if ($eventPackage) {
            $event->setRelation('eventPackage', $eventPackage);
        }

        $checkout = $this->checkoutService->createCheckout(
            $request->attributes->get('tenant'),
            $event,
            $request->validated(),
        );

        return response()->json([
            'checkout_url' => $checkout['checkout_url'] ?? null,
            'checkout_id' => $checkout['id'] ?? null,
            'expires_at' => $checkout['expires_at'] ?? null,
        ]);
    }

    public function apply(EventAddonRequest $request, Event $event): JsonResponse
    {
        $tenantId = $request->attributes->get('tenant_id');

        if ($event->tenant_id !== $tenantId) {
            return ApiError::response(
                'event_not_found',
                'Event not accessible',
                __('Das Event konnte nicht gefunden werden.'),
                404,
                ['event_slug' => $event->slug ?? null]
            );
        }

        $eventPackage = $event->eventPackage;

        if (! $eventPackage && method_exists($event, 'eventPackages')) {
            $eventPackage = $event->eventPackages()
                ->with('package')
                ->orderByDesc('purchased_at')
                ->orderByDesc('created_at')
                ->first();
        }

        if (! $eventPackage) {
            return ApiError::response(
                'event_package_missing',
                'Event package missing',
                __('Kein Paket ist diesem Event zugeordnet.'),
                409,
                ['event_slug' => $event->slug ?? null]
            );
        }

        $data = $request->validated();

        $eventPackage->fill([
            'extra_photos' => ($eventPackage->extra_photos ?? 0) + (int) ($data['extra_photos'] ?? 0),
            'extra_guests' => ($eventPackage->extra_guests ?? 0) + (int) ($data['extra_guests'] ?? 0),
            'extra_gallery_days' => ($eventPackage->extra_gallery_days ?? 0) + (int) ($data['extend_gallery_days'] ?? 0),
        ]);

        if (isset($data['extend_gallery_days'])) {
            $base = $eventPackage->gallery_expires_at ?? Carbon::now();
            $eventPackage->gallery_expires_at = $base->copy()->addDays((int) $data['extend_gallery_days']);
        }

        $eventPackage->save();

        $event->load([
            'eventPackage.package',
            'eventPackages.package',
        ]);

        return response()->json([
            'message' => __('Add-ons applied successfully.'),
            'data' => new EventResource($event),
        ]);
    }
}
