<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Services\DeviceTokenService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * Mints the "trusted device" token behind Quick PIN login. Called once per
 * full credential login (password, TOTP, or email-OTP — the method doesn't
 * matter, only that a real session was just established).
 */
class DeviceTokenController extends Controller
{
    public function __construct(private readonly DeviceTokenService $deviceTokens) {}

    public function store(Request $request): JsonResponse
    {
        $user = $request->user();

        // No device token for accounts Quick PIN can never log in:
        //  - no PIN set → there is nothing to unlock with;
        //  - TOTP/email-OTP enabled → PinLoginController refuses by design.
        // Without this the token would be minted for everyone and the login
        // page would offer a PIN pad to users who don't have one.
        if (! $user->canUseQuickLogin()) {
            return response()->json([
                'token' => null,
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'role' => $user->roles()->pluck('name')->first(),
                    'has_pin' => false,
                ],
            ]);
        }

        $token = $this->deviceTokens->issue($user);

        return response()->json([
            'token' => $token,
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'role' => $user->roles()->pluck('name')->first(),
                'has_pin' => true,
            ],
        ]);
    }
}
