<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Support\LocaleConfig;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class RegisteredUserController extends Controller
{
    /**
     * Show the registration page.
     */
    public function create(Request $request): RedirectResponse
    {
        return $this->redirectToPackages($request);
    }

    /**
     * Handle an incoming registration request.
     */
    public function store(Request $request): RedirectResponse|JsonResponse
    {
        if ($request->expectsJson()) {
            return response()->json([
                'message' => 'Registration is only available during checkout.',
            ], 410);
        }

        return $this->redirectToPackages($request);
    }

    private function redirectToPackages(Request $request): RedirectResponse
    {
        $preferredLocale = $request->session()->get('preferred_locale')
            ?? $request->getPreferredLanguage(LocaleConfig::normalized());
        $locale = LocaleConfig::canonicalize($request->route('locale') ?? $preferredLocale);
        $packageId = $request->input('package_id');
        $routeParams = ['locale' => $locale];

        if ($packageId) {
            $routeParams['package_id'] = $packageId;
        }

        return redirect()->route('packages', $routeParams);
    }
}
