<?php
namespace App\Services;

use App\DTOs\Auth\LoginDTO;
use App\DTOs\Auth\RegisterDTO;
use App\DTOs\Auth\UpdateUserDTO;
use App\Models\Role;
use App\Models\User;
use Exception;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class AuthService
{
    public function attemptLogin(LoginDTO $dto): bool
    {
        return Auth::attempt([
            'email' => $dto->email,
            'password' => $dto->password,
        ]);
    }

    public function register(RegisterDTO $dto, string $rolName = 'admin', bool $signIn = false): ?User
    {
        try {
            $user = User::create([
                'name' => $dto->name,
                'email' => $dto->email,
                'password' => Hash::make($dto->password),
            ]);
            $rolFind = Role::where('name', $rolName)->first();
            if ($signIn) {
                Auth::login($user);
            }
            $user->roles()->syncWithoutDetaching([$rolFind->id]);
            return $user;
        } catch (Exception $e) {
            Log::error('Error al crear usuario: ' . $e->getMessage(), [
                'data' => $dto,
                'trace' => $e->getTraceAsString(),
            ]);
            return null;
        }
    }

    public function update(int $userId, UpdateUserDTO $dto): ?User
    {
        try {
            $user = User::findOrFail($userId);

            $user->update([
                'name' => $dto->name,
                'email' => $dto->email,
                'password' => $dto->password ? Hash::make($dto->password) : $user->password,
            ]);

            return $user;
        } catch (Exception $e) {
            Log::error('Error al actualizar usuario: ' . $e->getMessage(), [
                'user_id' => $userId,
                'data' => $dto,
                'trace' => $e->getTraceAsString(),
            ]);
            return null;
        }
    }


    public function logout(): void
    {
        Auth::logout();
    }
}