<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Support\TrackerBoot;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

/**
 * Session login for the SPA. Same-origin cookies, no tokens to juggle — but the
 * CSRF token changes when the session is regenerated, so every answer carries
 * the fresh one for the app to keep using.
 */
class AuthController extends Controller
{
    public function login(Request $request): JsonResponse
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required', 'string'],
        ], [
            'required' => ':attribute দিতে হবে।',
            'email' => 'ইমেইলটা ঠিক নয়।',
        ], [
            'email' => 'ইমেইল',
            'password' => 'পাসওয়ার্ড',
        ]);

        if (! Auth::attempt($credentials, $request->boolean('remember'))) {
            // Reported against the email field, so which one was wrong stays unsaid.
            throw ValidationException::withMessages([
                'email' => 'ইমেইল বা পাসওয়ার্ড মেলেনি।',
            ]);
        }

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

        return response()->json([
            'message' => 'স্বাগতম, '.Auth::user()->name.'!',
            'auth' => TrackerBoot::auth(),
            'csrf_token' => csrf_token(),
        ]);
    }

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

        return response()->json([
            'message' => 'লগআউট হয়েছে।',
            'auth' => TrackerBoot::auth(),
            'csrf_token' => csrf_token(),
        ]);
    }
}
