/*
  Warnings:

  - You are about to drop the column `error_message` on the `sale_invoice_tsp_attempts` table. All the data in the column will be lost.
  - You are about to drop the column `tax_id` on the `sale_invoice_tsp_attempts` table. All the data in the column will be lost.
  - A unique constraint covering the columns `[tax_id]` on the table `sales_invoices` will be added. If there are existing duplicate values, this will fail.
  - Added the required column `message` to the `sale_invoice_tsp_attempts` table without a default value. This is not possible if the table is not empty.

*/
-- 1) Add new columns in a backward-compatible way
ALTER TABLE `sale_invoice_tsp_attempts`
    ADD COLUMN `message` TEXT NULL;

ALTER TABLE `sales_invoices`
    ADD COLUMN `tax_id` VARCHAR(32) NULL;

-- 2) Backfill message from old error_message, fallback to a default text
UPDATE `sale_invoice_tsp_attempts`
SET `message` = COALESCE(`error_message`, 'وضعیت ارسال فاکتور ثبت شد.')
WHERE `message` IS NULL;

-- 3) Backfill tax_id to sales_invoices from attempts
UPDATE `sales_invoices` si
JOIN `sale_invoice_tsp_attempts` sita ON sita.`invoice_id` = si.`id`
SET si.`tax_id` = sita.`tax_id`
WHERE sita.`tax_id` IS NOT NULL
  AND si.`tax_id` IS NULL;

-- 4) Enforce required constraint after backfill
ALTER TABLE `sale_invoice_tsp_attempts`
    MODIFY `message` TEXT NOT NULL;

-- 5) Remove old indexes/columns after successful data move
DROP INDEX `sale_invoice_tsp_attempts_tax_id_idx` ON `sale_invoice_tsp_attempts`;
DROP INDEX `sale_invoice_tsp_attempts_tax_id_key` ON `sale_invoice_tsp_attempts`;

ALTER TABLE `sale_invoice_tsp_attempts`
    DROP COLUMN `error_message`,
    DROP COLUMN `tax_id`;

-- 6) Add indexes on new tax_id location
CREATE UNIQUE INDEX `sales_invoices_tax_id_key` ON `sales_invoices`(`tax_id`);
CREATE INDEX `sales_invoices_tax_id_idx` ON `sales_invoices`(`tax_id`);
