<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Modules\Wishlist\Contracts\WishlistInterface;
use Daylight\Core\Modules\Cart\Contracts\CartInterface;
use Daylight\Core\Modules\Multilingualism\Entities\LocalizedRoute;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class LoginController extends Controller
{
    public function create(): View
    {
        if (request()->has('intended')) {
            session()->put('url.intended', request()->input('intended'));
        }

        $localizedRoute = LocalizedRoute::create()
            ->setRoute('login')
            ->staticRoute();

        return view('auth.login', [
            'localizedRoute' => $localizedRoute,
        ]);
    }

    public function store(LoginRequest $request): RedirectResponse|View
    {
        $request->authenticate();
        $request->session()->regenerate();

        app(CartInterface::class)->associate($request->user());
        app(WishlistInterface::class)->associate($request->user());

        return redirect()->intended(translatedRoute('account.index', absolute: false));
    }

    public function destroy(Request $request): RedirectResponse
    {
        Auth::guard('web')->logout();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->translatedRoute('page');
    }
}
