-- Migração adicional para correções e índices

USE saas_barbearia;

-- Adicionar campos que podem estar faltando
ALTER TABLE companies ADD COLUMN IF NOT EXISTS slug VARCHAR(255) UNIQUE AFTER name;
ALTER TABLE companies ADD COLUMN IF NOT EXISTS domain VARCHAR(255) UNIQUE AFTER slug;
ALTER TABLE companies ADD COLUMN IF NOT EXISTS status ENUM('active', 'inactive', 'suspended') DEFAULT 'active' AFTER address;

-- Atualizar dados existentes se necessário
UPDATE companies SET slug = LOWER(REPLACE(REPLACE(REPLACE(name, ' ', '-'), 'ã', 'a'), 'ç', 'c')) WHERE slug IS NULL;
UPDATE companies SET domain = CONCAT(slug, '.saas.com') WHERE domain IS NULL AND slug IS NOT NULL;

-- Garantir que índices existem
CREATE INDEX IF NOT EXISTS idx_companies_slug ON companies(slug);
CREATE INDEX IF NOT EXISTS idx_companies_domain ON companies(domain);
CREATE INDEX IF NOT EXISTS idx_companies_status ON companies(status);

-- Adicionar campos de auditoria se não existirem
ALTER TABLE users ADD COLUMN IF NOT EXISTS last_login TIMESTAMP NULL AFTER status;
ALTER TABLE services ADD COLUMN IF NOT EXISTS status ENUM('active', 'inactive') DEFAULT 'active' AFTER duration;

-- Popular slug para empresa existente se vazio
SET @company_name = (SELECT name FROM companies WHERE id = 1);
UPDATE companies SET slug = 'barbearia-exemplo' WHERE id = 1 AND (slug IS NULL OR slug = '');