<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Enums\UserRole;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;

class LoginController extends Controller
{
    public function store(Request $request)
    {
        $credentials = $request->validate([
            'username' => ['required', 'string'],
            'password' => ['required', 'string'],
        ]);

        $remember = $request->boolean('remember');

        if (Auth::attempt(['username' => $credentials['username'], 'password' => $credentials['password']], $remember)) {
            // Regenerate session to prevent fixation
            $request->session()->regenerate();

            // If the user asked to be remembered, set a cookie with the username so we can
            // pre-fill the username field next time. We deliberately DO NOT store the password
            // in a cookie for security reasons. The Laravel "remember" feature keeps the
            // user logged in across sessions using a secure remember_token.
            if ($remember) {
                // Cookie duration is in minutes (30 days)
                Cookie::queue('remember_username', $credentials['username'], 60 * 24 * 30);
            } else {
                Cookie::queue(Cookie::forget('remember_username'));
            }

            // Redirect based on user role
            $user = Auth::user();
            if ($user->role === UserRole::CUSTOMER) {
                return redirect()->intended('/catalog');
            }
            if ($user->role === UserRole::WINEMAKER) {
                return redirect()->intended('/winemaker/dashboard');
            }
            if ($user->role === UserRole::EMPLOYEE) {
                return redirect()->intended('/employee/tasks');
            }
            if ($user->role === UserRole::ADMIN) {
                return redirect()->intended('/admin/users');
            }

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

        return back()->withErrors(['username' => 'The provided credentials do not match our records.'])->onlyInput('username');
    }

    public function destroy(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect()->route('login');
    }
}
