<?php

namespace App\Http\Controllers\SaasAdmin;

use App\Http\Controllers\Controller;
use App\Repositories\UserRepository;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\View\View;

/**
 * Its own login, deliberately separate from the tenant-facing
 * auth/login.blade.php — a company admin's credentials should never even
 * be checked against this form, and vice versa.
 */
class AuthController extends Controller
{
    public function index(): View|RedirectResponse
    {
        $user = Auth::user();

        if ($user && $user->is_root && $user->company_id === null) {
            return to_route('saas-admin.companies.index');
        }

        return view('saas-admin.auth.login');
    }

    public function authenticate(Request $request): RedirectResponse
    {
        $credentials = $request->validate([
            'email' => ['required'],
            'password' => ['required'],
        ]);

        $user = UserRepository::query()->where('email', $credentials['email'])->first();

        if (!$user || !$user->is_root || $user->company_id !== null) {
            return back()->withErrors([
                'email' => 'The provided credentials do not match our records.',
            ])->onlyInput('email');
        }

        if (!Hash::check($credentials['password'], $user->password)) {
            return back()->withErrors([
                'password' => 'The password you entered is incorrect.',
            ])->onlyInput('email');
        }

        Auth::login($user, true);
        $request->session()->regenerate();

        return to_route('saas-admin.companies.index');
    }

    public function logout(Request $request): RedirectResponse
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return to_route('saas-admin.login');
    }
}
