<?php

declare(strict_types=1);

namespace ImovelZapAi\Authentication\Infrastructure\Http\Controllers\Web;

use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use ImovelZapAi\Authentication\Application\Actions\RegisterAccountAction;
use ImovelZapAi\Authentication\Application\Actions\WebLoginAction;
use ImovelZapAi\Authentication\Infrastructure\Http\Requests\WebLoginRequest;
use ImovelZapAi\Authentication\Infrastructure\Http\Requests\WebRegisterRequest;
use ImovelZapAi\Tenancy\Support\TenantContext;

final class AuthController
{
    public function showLogin(): View
    {
        return view('auth.login');
    }

    public function login(WebLoginRequest $request, WebLoginAction $action): RedirectResponse
    {
        $action->execute(
            email: $request->string('email')->toString(),
            password: $request->string('password')->toString(),
            remember: $request->boolean('remember'),
        );

        $request->session()->regenerate();

        return redirect()->intended(route('dashboard'));
    }

    public function showRegister(): View
    {
        return view('auth.register');
    }

    public function register(WebRegisterRequest $request, RegisterAccountAction $action): RedirectResponse
    {
        try {
            $action->execute(
                accountType: $request->string('account_type')->toString(),
                name: $request->string('name')->toString(),
                email: $request->string('email')->toString(),
                password: $request->string('password')->toString(),
                organizationName: $request->input('organization_name'),
                loginAfter: true,
            );
        } catch (ValidationException $exception) {
            throw $exception;
        }

        $request->session()->regenerate();

        return redirect()
            ->route('verification.notice')
            ->with('status', 'Conta criada. Confirme seu e-mail para continuar.');
    }

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

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

        TenantContext::clear();

        return redirect()->route('login');
    }
}
