<?php

namespace Tests\Modules\Compras;

use Tests\TestCase;

/**
 * Testes para o módulo Compras
 */
class PurchasesTest extends TestCase {
    
    protected function setUp(): void {
        parent::setUp();
        
        // Criar tabela de fornecedores
        $this->pdo->exec('
            CREATE TABLE IF NOT EXISTS suppliers (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                tenant_id VARCHAR(100) NOT NULL,
                nome VARCHAR(255) NOT NULL,
                cpf_cnpj VARCHAR(20),
                email VARCHAR(255),
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ');
        
        // Criar tabela de pedidos de compra
        $this->pdo->exec('
            CREATE TABLE IF NOT EXISTS purchase_orders (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                tenant_id VARCHAR(100) NOT NULL,
                numero VARCHAR(50) NOT NULL,
                supplier_id INTEGER NOT NULL,
                status VARCHAR(20) DEFAULT "rascunho",
                total DECIMAL(18,2) DEFAULT 0,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ');
        
        // Criar tabela de itens de pedido de compra
        $this->pdo->exec('
            CREATE TABLE IF NOT EXISTS purchase_order_items (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                tenant_id VARCHAR(100) NOT NULL,
                order_id INTEGER NOT NULL,
                product_id INTEGER NOT NULL,
                quantidade DECIMAL(18,3) NOT NULL,
                preco_unitario DECIMAL(18,2) NOT NULL,
                total DECIMAL(18,2) NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ');
    }
    
    public function testCreatePurchaseOrder(): void {
        // Criar fornecedor
        $stmt = $this->pdo->prepare('
            INSERT INTO suppliers (tenant_id, nome, cpf_cnpj, email)
            VALUES (?, ?, ?, ?)
        ');
        $stmt->execute([$this->tenantId, 'Test Supplier', '12345678000100', 'supplier@example.com']);
        $supplierId = (int)$this->pdo->lastInsertId();
        
        $productId = $this->createTestProduct(['preco' => 50.00]);
        
        // Criar pedido de compra
        $stmt = $this->pdo->prepare('
            INSERT INTO purchase_orders (tenant_id, numero, supplier_id, status, total)
            VALUES (?, ?, ?, ?, ?)
        ');
        $stmt->execute([$this->tenantId, 'COMP001', $supplierId, 'rascunho', 0]);
        $orderId = (int)$this->pdo->lastInsertId();
        
        // Adicionar item
        $stmt = $this->pdo->prepare('
            INSERT INTO purchase_order_items (tenant_id, order_id, product_id, quantidade, preco_unitario, total)
            VALUES (?, ?, ?, ?, ?, ?)
        ');
        $stmt->execute([$this->tenantId, $orderId, $productId, 10.0, 50.00, 500.00]);
        
        // Atualizar total
        $stmt = $this->pdo->prepare('
            UPDATE purchase_orders 
            SET total = (SELECT SUM(total) FROM purchase_order_items WHERE order_id = ?)
            WHERE id = ?
        ');
        $stmt->execute([$orderId, $orderId]);
        
        // Verificar pedido
        $stmt = $this->pdo->prepare('SELECT * FROM purchase_orders WHERE id = ?');
        $stmt->execute([$orderId]);
        $order = $stmt->fetch();
        
        $this->assertNotFalse($order);
        $this->assertEquals('COMP001', $order['numero']);
        $this->assertEquals(500.00, $order['total']);
    }
    
    public function testReceivePurchaseOrder(): void {
        // Criar fornecedor
        $stmt = $this->pdo->prepare('
            INSERT INTO suppliers (tenant_id, nome, cpf_cnpj, email)
            VALUES (?, ?, ?, ?)
        ');
        $stmt->execute([$this->tenantId, 'Test Supplier', '12345678000100', 'supplier@example.com']);
        $supplierId = (int)$this->pdo->lastInsertId();
        
        $productId = $this->createTestProduct(['estoque' => 10.0]);
        
        // Criar pedido de compra
        $stmt = $this->pdo->prepare('
            INSERT INTO purchase_orders (tenant_id, numero, supplier_id, status, total)
            VALUES (?, ?, ?, ?, ?)
        ');
        $stmt->execute([$this->tenantId, 'COMP002', $supplierId, 'aprovado', 0]);
        $orderId = (int)$this->pdo->lastInsertId();
        
        // Adicionar item
        $quantidade = 20.0;
        $stmt = $this->pdo->prepare('
            INSERT INTO purchase_order_items (tenant_id, order_id, product_id, quantidade, preco_unitario, total)
            VALUES (?, ?, ?, ?, ?, ?)
        ');
        $stmt->execute([$this->tenantId, $orderId, $productId, $quantidade, 50.00, 1000.00]);
        
        // Receber pedido (atualizar estoque)
        $stmt = $this->pdo->prepare('
            UPDATE products 
            SET estoque = estoque + ?
            WHERE id = ? AND tenant_id = ?
        ');
        $stmt->execute([$quantidade, $productId, $this->tenantId]);
        
        // Atualizar status
        $stmt = $this->pdo->prepare('
            UPDATE purchase_orders 
            SET status = "recebido"
            WHERE id = ?
        ');
        $stmt->execute([$orderId]);
        
        // Verificar estoque
        $stmt = $this->pdo->prepare('SELECT estoque FROM products WHERE id = ?');
        $stmt->execute([$productId]);
        $product = $stmt->fetch();
        
        $this->assertEquals(30.0, $product['estoque']);
        
        // Verificar status
        $stmt = $this->pdo->prepare('SELECT status FROM purchase_orders WHERE id = ?');
        $stmt->execute([$orderId]);
        $order = $stmt->fetch();
        
        $this->assertEquals('recebido', $order['status']);
    }
}

