ALTER TABLE empresas
    ADD COLUMN slug VARCHAR(120) NULL AFTER nombre;

UPDATE empresas
SET slug = CONCAT('empresa-', id)
WHERE slug IS NULL OR slug = '';

ALTER TABLE empresas
    MODIFY COLUMN slug VARCHAR(120) NOT NULL,
    ADD UNIQUE KEY uk_empresas_slug (slug);

CREATE TABLE IF NOT EXISTS saas_checkout_intents (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    reference VARCHAR(80) NOT NULL,
    plan_id BIGINT UNSIGNED NOT NULL,
    empresa_nombre VARCHAR(150) NOT NULL,
    empresa_slug VARCHAR(120) NOT NULL,
    empresa_email VARCHAR(180) NULL,
    admin_nombre VARCHAR(150) NOT NULL,
    admin_email VARCHAR(180) NOT NULL,
    admin_password_hash VARCHAR(255) NOT NULL,
    currency VARCHAR(10) NOT NULL DEFAULT 'COP',
    amount_in_cents INT UNSIGNED NOT NULL,
    estado ENUM('pending', 'approved', 'declined', 'error', 'voided', 'provisioned', 'failed') NOT NULL DEFAULT 'pending',
    wompi_transaction_id VARCHAR(80) NULL,
    wompi_status VARCHAR(40) NULL,
    last_event_at DATETIME NULL,
    paid_at DATETIME NULL,
    empresa_id BIGINT UNSIGNED NULL,
    suscripcion_id BIGINT UNSIGNED NULL,
    provisioned_at DATETIME NULL,
    failure_reason VARCHAR(255) NULL,
    created_at DATETIME NULL,
    updated_at DATETIME NULL,
    UNIQUE KEY uk_saas_checkout_reference (reference),
    INDEX idx_saas_checkout_plan (plan_id),
    INDEX idx_saas_checkout_admin_email (admin_email),
    INDEX idx_saas_checkout_status (estado),
    CONSTRAINT fk_saas_checkout_plan FOREIGN KEY (plan_id) REFERENCES planes(id),
    CONSTRAINT fk_saas_checkout_empresa FOREIGN KEY (empresa_id) REFERENCES empresas(id),
    CONSTRAINT fk_saas_checkout_suscripcion FOREIGN KEY (suscripcion_id) REFERENCES suscripciones(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
