<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Services\SingleSessionService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class TokenController extends Controller
{
    public function __construct(
        protected SingleSessionService $singleSessionService
    ) {
    }

    /**
     * Create a new API token for the user.
     */
    public function store(Request $request)
    {
        $request->validate([
            'email' => ['required', 'string', 'email'],
            'password' => ['required', 'string'],
            'device_name' => ['required', 'string'],
        ]);

        if (! Auth::attempt($request->only('email', 'password'))) {
            throw ValidationException::withMessages([
                'email' => __('auth.failed'),
            ]);
        }

        $user = Auth::user();

        // Enforce single session policy untuk User saja
        // Revoke semua token sebelumnya sebelum create token baru
        $this->singleSessionService->enforceSingleSession($user);

        $token = $user->createToken($request->device_name)->plainTextToken;

        return response()->json([
            'token' => $token,
            'user' => $user,
        ]);
    }

    /**
     * Revoke all tokens for the authenticated user.
     */
    public function destroy(Request $request)
    {
        $request->user()->tokens()->delete();

        return response()->noContent();
    }
}

