<?php

namespace App\Services;

use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class AuthService
{
    public function attemptWebLogin(array $credentials): bool
    {
        $user = User::where('email', $credentials['email'])->first();

        if (! $user || ! Hash::check($credentials['password'], $user->password)) {
            return false;
        }

        // Verificar se é admin ou staff
        if (! in_array($user->type, ['admin', 'staff'])) {
            return false;
        }

        // Verificar se está ativo
        if (! $user->isActive()) {
            return false;
        }

        Auth::login($user, isset($credentials['remember']));

        return true;
    }

    public function attemptApiLogin(array $credentials): array
    {
        $user = User::where('email', $credentials['email'])->first();

        if (! $user || ! Hash::check($credentials['password'], $user->password)) {
            return ['success' => false];
        }

        // Verificar se é fiscal
        if ($user->type !== 'fiscal') {
            return ['success' => false];
        }

        // Verificar se está ativo
        if (! $user->isActive()) {
            return ['success' => false];
        }

        // Criar token Sanctum
        $token = $user->createToken('fiscal-token')->plainTextToken;

        return [
            'success' => true,
            'user' => $user->load(['fiscal', 'roles.permissions']),
            'token' => $token,
        ];
    }

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