-- Safe 4-step migration to add invoice_download_token to existing sales table.
-- Step 1: Add column as NULL first (safe for tables with existing rows)
ALTER TABLE `sales` ADD COLUMN `invoice_download_token` CHAR(36) NULL;

-- Step 2: Populate existing rows with unique UUIDs
UPDATE `sales` SET `invoice_download_token` = UUID() WHERE `invoice_download_token` IS NULL;

-- Step 3: Add unique index (all values are now distinct UUIDs)
ALTER TABLE `sales` ADD UNIQUE INDEX `uq_sales_invoice_download_token` (`invoice_download_token`);

-- Step 4: Make column NOT NULL with DB-side default for new rows
ALTER TABLE `sales` MODIFY `invoice_download_token` CHAR(36) NOT NULL DEFAULT (UUID());
