<?php

namespace App\Services;

use App\Models\User;
use App\Repositories\Eloquent\UserRepository;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthService
{
    protected UserRepository $userRepository;
    protected LoggingService $loggingService;

    public function __construct(UserRepository $userRepository, LoggingService $loggingService)
    {
        $this->userRepository = $userRepository;
        $this->loggingService = $loggingService;
    }

    public function register(array $data): array
    {
        $this->loggingService->logService('AuthService::register', ['email' => $data['email']]);

        $user = $this->userRepository->createWithRole([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => $data['password'],
            'branch_id' => $data['branch_id'] ?? null,
        ], $data['role'] ?? 'pos-operator');

        $token = $user->createToken('auth-token')->plainTextToken;

        $user->load(['roles', 'permissions', 'branch']);

        $this->loggingService->logService('AuthService::register', null, "User {$user->id} registered");

        return [
            'user' => $user,
            'token' => $token,
        ];
    }

    public function login(array $credentials): array
    {
        $this->loggingService->logService('AuthService::login', ['email' => $credentials['email']]);

        $user = $this->userRepository->findByEmail($credentials['email']);

        if (!$user || !Hash::check($credentials['password'], $user->password)) {
            $this->loggingService->logError('Invalid credentials', ['email' => $credentials['email']]);
            throw ValidationException::withMessages([
                'email' => ['The provided credentials are incorrect.'],
            ]);
        }

        $user->tokens()->delete();
        $token = $user->createToken('auth-token')->plainTextToken;

        $user->load(['roles', 'permissions', 'branch']);

        $this->loggingService->logService('AuthService::login', null, "User {$user->id} logged in");

        return [
            'user' => $user,
            'token' => $token,
        ];
    }

    public function logout(User $user): void
    {
        $this->loggingService->logService('AuthService::logout', ['user_id' => $user->id]);

        $user->currentAccessToken()->delete();

        $this->loggingService->logService('AuthService::logout', null, "User {$user->id} logged out");
    }

    public function refreshToken(User $user): string
    {
        $this->loggingService->logService('AuthService::refreshToken', ['user_id' => $user->id]);

        $user->currentAccessToken()->delete();
        $token = $user->createToken('auth-token')->plainTextToken;

        $this->loggingService->logService('AuthService::refreshToken', null, "Token refreshed for user {$user->id}");

        return $token;
    }

    public function getAuthenticatedUser(User $user): User
    {
        return $user->load(['roles', 'permissions', 'branch']);
    }
}
