-- 1. Add the new columns
ALTER TABLE `sale_invoice_tsp_attempts`
    ADD COLUMN `error_message` TEXT NULL,
    ADD COLUMN `fiscal_warnings` JSON NULL,
    ADD COLUMN `provider_response` JSON NULL,
    ADD COLUMN `validation_errors` JSON NULL;

-- 2. Copy data from the old column to the new JSON column
-- Note: We use a check to ensure we don't try to move invalid data
UPDATE `sale_invoice_tsp_attempts`
SET `provider_response` = CAST(`provider_response_payload` AS JSON)
WHERE `provider_response_payload` IS NOT NULL AND JSON_VALID(`provider_response_payload`);

-- 3. SANITIZE 'provider_request_payload' before converting to JSON
-- This replaces empty strings or invalid JSON with a default empty object '{}'
UPDATE `sale_invoice_tsp_attempts`
SET `provider_request_payload` = '{}'
WHERE `provider_request_payload` IS NULL
   OR `provider_request_payload` = ''
   OR JSON_VALID(`provider_request_payload`) = 0;

-- 4. Perform the final modifications and drop the old column
ALTER TABLE `sale_invoice_tsp_attempts`
    DROP COLUMN `provider_response_payload`,
    MODIFY `status` ENUM('NOT_SEND', 'QUEUED', 'FISCAL_QUEUED', 'SEND_FAILURE', 'SUCCESS', 'FAILURE') NOT NULL,
    MODIFY `provider_request_payload` JSON NOT NULL;
