<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Services\ActivityLogger;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class AuthenticatedSessionController extends Controller
{
    public function create(): View
    {
        return view('auth.login');
    }

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

        if (! Auth::attempt($credentials, $request->boolean('remember'))) {
            return back()->withErrors(['email' => 'The provided credentials do not match our records.'])->onlyInput('email');
        }

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

        if ($user->status !== 'active') {
            Auth::logout();

            return back()->withErrors(['email' => 'Your account is inactive. Contact your administrator.']);
        }

        $user->forceFill(['last_login_at' => now()])->save();
        ActivityLogger::log('login', $user->name.' signed in.');

        return redirect()->intended(
            match (true) {
                $user->isSuperAdmin() => route('super.dashboard'),
                $user->role === User::ROLE_AGENT => route('merchant.dashboard'),
                $user->role === User::ROLE_CUSTOMER => route('member.dashboard'),
                default => route('tenant.dashboard'),
            }
        );
    }

    public function destroy(Request $request): RedirectResponse
    {
        ActivityLogger::log('logout', $request->user()?->name.' signed out.');
        Auth::logout();

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

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