<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\LoginRequest;
use App\Services\AuthService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    protected AuthService $authService;

    public function __construct(AuthService $authService)
    {
        $this->authService = $authService;
    }

    public function login(LoginRequest $request): JsonResponse
    {
        $credentials = $request->validated();

        $result = $this->authService->attemptApiLogin($credentials);

        if ($result['success']) {
            return response()->json([
                'success' => true,
                'user' => $result['user'],
                'token' => $result['token'],
                'token_type' => 'Bearer',
            ]);
        }

        return response()->json([
            'success' => false,
            'message' => 'Credenciais inválidas',
        ], 401);
    }

    public function logout(): JsonResponse
    {
        Auth::user()->currentAccessToken()->delete();

        return response()->json([
            'success' => true,
            'message' => 'Logout realizado com sucesso',
        ]);
    }

    public function profile(): JsonResponse
    {
        return response()->json([
            'success' => true,
            'user' => Auth::user()->load(['fiscal', 'roles.permissions']),
        ]);
    }
}
