/*
  Warnings:

  - You are about to drop the column `request_payload` on the `sale_invoice_tsp_attempts` table. All the data in the column will be lost.
  - You are about to drop the column `response_payload` on the `sale_invoice_tsp_attempts` table. All the data in the column will be lost.
  - Added the required column `raw_request_payload` to the `sale_invoice_tsp_attempts` table without a default value. This is not possible if the table is not empty.

*/
-- DropForeignKey
ALTER TABLE `sale_invoice_tsp_attempts` DROP FOREIGN KEY `sale_invoice_tsp_attempts_invoice_id_fkey`;

-- DropIndex
DROP INDEX `sale_invoice_tsp_attempts_invoice_id_key` ON `sale_invoice_tsp_attempts`;

-- AlterTable
ALTER TABLE `sale_invoice_tsp_attempts`
    ADD COLUMN `provider_request_payload` JSON NULL,
    ADD COLUMN `provider_response_payload` JSON NULL,
    ADD COLUMN `raw_request_payload` JSON NOT NULL;

UPDATE `sale_invoice_tsp_attempts`
  SET `provider_response_payload` = `response_payload`;
UPDATE `sale_invoice_tsp_attempts`
  SET `raw_request_payload` = `request_payload`;

ALTER TABLE `sale_invoice_tsp_attempts`
    DROP COLUMN `response_payload`,
    DROP COLUMN `request_payload`;

-- AddForeignKey
-- Check if the foreign key constraint already exists before adding it
SET @constraint_exists = (
  SELECT COUNT(*)
  FROM information_schema.TABLE_CONSTRAINTS
  WHERE CONSTRAINT_SCHEMA = DATABASE()
    AND TABLE_NAME = 'customer_legal'
    AND CONSTRAINT_NAME = 'customer_legal_business_activity_id_fkey'
    AND CONSTRAINT_TYPE = 'FOREIGN KEY'
);

SET @sql = IF(@constraint_exists = 0,
  'ALTER TABLE `customer_legal` ADD CONSTRAINT `customer_legal_business_activity_id_fkey` FOREIGN KEY (`business_activity_id`) REFERENCES `business_activities`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;',
  'SELECT "Foreign key constraint customer_legal_business_activity_id_fkey already exists" as message;'
);

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