-- Tabela de clientes (pessoas físicas e jurídicas)
CREATE TABLE IF NOT EXISTS clientes (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    tipo ENUM('pessoa_fisica', 'pessoa_juridica') NOT NULL,
    nome_completo VARCHAR(255) NOT NULL,
    razao_social VARCHAR(255) NULL,
    nome_fantasia VARCHAR(255) NULL,
    cpf VARCHAR(14) NULL,
    cnpj VARCHAR(18) NULL,
    email VARCHAR(255) NOT NULL UNIQUE,
    telefone VARCHAR(20) NULL,
    whatsapp VARCHAR(20) NULL,
    password VARCHAR(255) NOT NULL,
    email_verified_at TIMESTAMP NULL,
    remember_token VARCHAR(100) NULL,
    ativo BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    INDEX idx_email (email),
    INDEX idx_cpf (cpf),
    INDEX idx_cnpj (cnpj)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Tabela de favoritos (relacionamento muitos-para-muitos entre clientes e transportadoras)
CREATE TABLE IF NOT EXISTS clientes_favoritos (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    cliente_id BIGINT UNSIGNED NOT NULL,
    transportadora_id BIGINT UNSIGNED NOT NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    UNIQUE KEY unique_favorito (cliente_id, transportadora_id),
    FOREIGN KEY (cliente_id) REFERENCES clientes(id) ON DELETE CASCADE,
    FOREIGN KEY (transportadora_id) REFERENCES transportadoras(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Adicionar coluna cliente_id na tabela orcamentos (se ainda não existir)
-- Verificar se a coluna já existe antes de adicionar
SET @col_exists = (
    SELECT COUNT(*) 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_SCHEMA = DATABASE() 
    AND TABLE_NAME = 'orcamentos' 
    AND COLUMN_NAME = 'cliente_id'
);

SET @sql = IF(@col_exists = 0,
    'ALTER TABLE orcamentos ADD COLUMN cliente_id BIGINT UNSIGNED NULL AFTER id, ADD INDEX idx_cliente_id (cliente_id), ADD FOREIGN KEY (cliente_id) REFERENCES clientes(id) ON DELETE SET NULL',
    'SELECT "Coluna cliente_id já existe na tabela orcamentos" AS message'
);

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
