<?php

namespace Tests\Modules\Auth;

use Tests\TestCase;
use PDO;

/**
 * Testes para o módulo Auth
 */
class AuthTest extends TestCase {
    
    public function testCreateUser(): void {
        $userId = $this->createTestUser([
            'email' => 'newuser@example.com',
            'nome' => 'New User'
        ]);
        
        $this->assertIsInt($userId);
        $this->assertGreaterThan(0, $userId);
        
        // Verificar se o usuário foi criado
        $stmt = $this->pdo->prepare('SELECT * FROM users WHERE id = ?');
        $stmt->execute([$userId]);
        $user = $stmt->fetch();
        
        $this->assertNotFalse($user);
        $this->assertEquals('newuser@example.com', $user['email']);
        $this->assertEquals('New User', $user['nome']);
        $this->assertEquals(1, $user['enabled']);
    }
    
    public function testUserLogin(): void {
        $userId = $this->createTestUser([
            'email' => 'login@example.com',
            'password' => password_hash('password123', PASSWORD_DEFAULT)
        ]);
        
        // Simular login
        $stmt = $this->pdo->prepare('SELECT * FROM users WHERE email = ? AND enabled = 1');
        $stmt->execute(['login@example.com']);
        $user = $stmt->fetch();
        
        $this->assertNotFalse($user);
        $this->assertTrue(password_verify('password123', $user['password']));
    }
    
    public function testUserDisabled(): void {
        $userId = $this->createTestUser([
            'email' => 'disabled@example.com',
            'enabled' => 0
        ]);
        
        // Tentar login com usuário desabilitado
        $stmt = $this->pdo->prepare('SELECT * FROM users WHERE email = ? AND enabled = 1');
        $stmt->execute(['disabled@example.com']);
        $user = $stmt->fetch();
        
        $this->assertFalse($user);
    }
    
    public function testTenantIsolation(): void {
        // Criar usuário no tenant de teste
        $userId1 = $this->createTestUser([
            'email' => 'user1@example.com'
        ]);
        
        // Criar usuário em outro tenant
        $stmt = $this->pdo->prepare('
            INSERT INTO users (tenant_id, email, password, nome, enabled)
            VALUES (?, ?, ?, ?, ?)
        ');
        $stmt->execute([
            'other-tenant',
            'user2@example.com',
            password_hash('password123', PASSWORD_DEFAULT),
            'User 2',
            1
        ]);
        
        // Verificar isolamento
        $stmt = $this->pdo->prepare('SELECT COUNT(*) as count FROM users WHERE tenant_id = ?');
        $stmt->execute([$this->tenantId]);
        $count = $stmt->fetch();
        
        $this->assertEquals(1, $count['count']);
    }
}

