<?php

namespace Tests;

use PHPUnit\Framework\TestCase as PHPUnitTestCase;
use PDO;

/**
 * Classe base para testes
 */
abstract class TestCase extends PHPUnitTestCase {
    protected PDO $pdo;
    protected string $tenantId = 'test-tenant-001';
    
    protected function setUp(): void {
        parent::setUp();
        
        // Criar conexão SQLite em memória para testes
        $this->pdo = new PDO('sqlite::memory:');
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        
        // Criar tabelas básicas
        $this->createBaseTables();
    }
    
    protected function tearDown(): void {
        // Limpar após cada teste
        $this->pdo = null;
        parent::tearDown();
    }
    
    /**
     * Cria tabelas básicas para testes
     */
    protected function createBaseTables(): void {
        // Tabela de tenants
        $this->pdo->exec('
            CREATE TABLE IF NOT EXISTS tenants (
                id VARCHAR(100) PRIMARY KEY,
                nome VARCHAR(255) NOT NULL,
                database_name VARCHAR(255) NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ');
        
        // Tabela de usuários
        $this->pdo->exec('
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                tenant_id VARCHAR(100) NOT NULL,
                email VARCHAR(255) NOT NULL,
                password VARCHAR(255) NOT NULL,
                nome VARCHAR(255) NOT NULL,
                enabled BOOLEAN DEFAULT 1,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ');
        
        // Tabela de produtos
        $this->pdo->exec('
            CREATE TABLE IF NOT EXISTS products (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                tenant_id VARCHAR(100) NOT NULL,
                codigo VARCHAR(100) NOT NULL,
                nome VARCHAR(255) NOT NULL,
                preco DECIMAL(18,2) DEFAULT 0,
                estoque DECIMAL(18,3) DEFAULT 0,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ');
        
        // Tabela de clientes
        $this->pdo->exec('
            CREATE TABLE IF NOT EXISTS clients (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                tenant_id VARCHAR(100) NOT NULL,
                nome VARCHAR(255) NOT NULL,
                email VARCHAR(255),
                cpf_cnpj VARCHAR(20),
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ');
        
        // Inserir tenant de teste
        $stmt = $this->pdo->prepare('INSERT OR IGNORE INTO tenants (id, nome, database_name) VALUES (?, ?, ?)');
        $stmt->execute([$this->tenantId, 'Test Tenant', 'test_db']);
    }
    
    /**
     * Helper para criar usuário de teste
     */
    protected function createTestUser(array $data = []): int {
        $stmt = $this->pdo->prepare('
            INSERT INTO users (tenant_id, email, password, nome, enabled)
            VALUES (?, ?, ?, ?, ?)
        ');
        $stmt->execute([
            $this->tenantId,
            $data['email'] ?? 'test@example.com',
            $data['password'] ?? password_hash('password123', PASSWORD_DEFAULT),
            $data['nome'] ?? 'Test User',
            $data['enabled'] ?? 1
        ]);
        return (int)$this->pdo->lastInsertId();
    }
    
    /**
     * Helper para criar produto de teste
     */
    protected function createTestProduct(array $data = []): int {
        $stmt = $this->pdo->prepare('
            INSERT INTO products (tenant_id, codigo, nome, preco, estoque)
            VALUES (?, ?, ?, ?, ?)
        ');
        $stmt->execute([
            $this->tenantId,
            $data['codigo'] ?? 'PROD001',
            $data['nome'] ?? 'Test Product',
            $data['preco'] ?? 100.00,
            $data['estoque'] ?? 10.0
        ]);
        return (int)$this->pdo->lastInsertId();
    }
    
    /**
     * Helper para criar cliente de teste
     */
    protected function createTestClient(array $data = []): int {
        $stmt = $this->pdo->prepare('
            INSERT INTO clients (tenant_id, nome, email, cpf_cnpj)
            VALUES (?, ?, ?, ?)
        ');
        $stmt->execute([
            $this->tenantId,
            $data['nome'] ?? 'Test Client',
            $data['email'] ?? 'client@example.com',
            $data['cpf_cnpj'] ?? '12345678901'
        ]);
        return (int)$this->pdo->lastInsertId();
    }
}

