CREATE TABLE finanto_inss_simulations (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    lead_id INT UNSIGNED NOT NULL,
    integration_id INT UNSIGNED NOT NULL,
    created_by INT UNSIGNED NULL,
    status VARCHAR(40) NOT NULL DEFAULT 'pending',
    simulation_id VARCHAR(80) NULL,
    messages JSON NULL,
    request_payload JSON NULL,
    response_payload JSON NULL,
    offers_payload JSON NULL,
    selected_offer JSON NULL,
    rejection_payload JSON NULL,
    converted_proposal_id INT UNSIGNED NULL,
    converted_at DATETIME NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
    CONSTRAINT fk_finanto_simulations_lead FOREIGN KEY (lead_id) REFERENCES leads (id) ON DELETE CASCADE,
    CONSTRAINT fk_finanto_simulations_integration FOREIGN KEY (integration_id) REFERENCES api_integrations (id) ON DELETE CASCADE,
    CONSTRAINT fk_finanto_simulations_user FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL,
    CONSTRAINT fk_finanto_simulations_proposal FOREIGN KEY (converted_proposal_id) REFERENCES loan_proposals (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE INDEX idx_finanto_simulations_status ON finanto_inss_simulations (status);
CREATE INDEX idx_finanto_simulations_lead ON finanto_inss_simulations (lead_id);
CREATE INDEX idx_finanto_simulations_integration ON finanto_inss_simulations (integration_id);
CREATE INDEX idx_finanto_simulations_created ON finanto_inss_simulations (created_at);
