<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Exceptions\PackageUnavailableException;
use App\Models\Experience;
use App\Models\Package;
use App\Services\Packages\PackageService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class PackageController extends Controller
{
    public function index(): View
    {
        return view('packages.index', [
            'packages' => Package::active()->orderBy('sort_order')->get(),
            'experiences' => Experience::active()->with('room')->orderBy('sort_order')->get(),
        ]);
    }

    public function buy(Request $request, Package $package, PackageService $packages): RedirectResponse
    {
        $validated = $request->validate([
            'as_group' => ['boolean'],
            'participants' => ['integer', 'min:1', 'max:10'],
        ]);

        // Sign-in is required before buying, because a package is credited to
        // an account rather than sold anonymously.
        if (! $request->user()) {
            return redirect()->guest(route('login'));
        }

        try {
            $purchase = $packages->purchase(
                $request->user(),
                $package,
                asGroup: (bool) ($validated['as_group'] ?? false),
                participants: (int) ($validated['participants'] ?? 1),
            );
        } catch (PackageUnavailableException $e) {
            // The message is written to be safe to show verbatim — it is the
            // age limit or the group size, not an internal failure.
            return back()->with('status', $e->getMessage());
        }

        return redirect()->route('package.checkout', $purchase->reference);
    }
}
