-- ============================================
-- FIX REFERRAL TABLES IF THEY EXIST WITH ERRORS
-- This will drop and recreate tables if needed
-- ============================================

-- WARNING: This will DELETE all referral data!
-- Only run this if you're okay with losing existing referral data

-- Step 1: Drop tables if they exist (this deletes all data!)
DROP TABLE IF EXISTS `referral_rewards`;
DROP TABLE IF EXISTS `referrals`;

-- Step 2: Recreate referrals table (NO UNIQUE on referralCode)
CREATE TABLE `referrals` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `referrerId` INT NOT NULL,
  `referrerType` ENUM('customer', 'supplier') NOT NULL,
  `referredCustomerId` INT NOT NULL,
  `referralCode` VARCHAR(50) NOT NULL,
  `status` ENUM('pending', 'active', 'completed', 'cancelled') DEFAULT 'pending',
  `totalEarnings` DECIMAL(10, 2) DEFAULT 0,
  `totalOrders` INT DEFAULT 0,
  `totalOrderValue` DECIMAL(10, 2) DEFAULT 0,
  `commissionRate` DECIMAL(5, 2) DEFAULT 0,
  `firstOrderCompleted` BOOLEAN DEFAULT FALSE,
  `firstOrderRewardPaid` BOOLEAN DEFAULT FALSE,
  `createdAt` DATETIME DEFAULT CURRENT_TIMESTAMP,
  `updatedAt` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  INDEX `idx_referrer` (`referrerId`),
  INDEX `idx_referred_customer` (`referredCustomerId`),
  INDEX `idx_referral_code` (`referralCode`),
  FOREIGN KEY (`referrerId`) REFERENCES `users`(`id`) ON DELETE CASCADE,
  FOREIGN KEY (`referredCustomerId`) REFERENCES `users`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Step 3: Recreate referral_rewards table
CREATE TABLE `referral_rewards` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `referralId` INT NOT NULL,
  `orderId` INT NULL,
  `rewardType` ENUM('first_order', 'commission', 'bonus') NOT NULL,
  `orderAmount` DECIMAL(10, 2) NOT NULL,
  `commissionRate` DECIMAL(5, 2) NOT NULL,
  `rewardAmount` DECIMAL(10, 2) NOT NULL,
  `status` ENUM('pending', 'paid', 'cancelled') DEFAULT 'pending',
  `paidAt` DATETIME NULL,
  `paidToWallet` BOOLEAN DEFAULT FALSE,
  `notes` TEXT NULL,
  `createdAt` DATETIME DEFAULT CURRENT_TIMESTAMP,
  `updatedAt` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  INDEX `idx_referral` (`referralId`),
  INDEX `idx_order` (`orderId`),
  INDEX `idx_status` (`status`),
  FOREIGN KEY (`referralId`) REFERENCES `referrals`(`id`) ON DELETE CASCADE,
  FOREIGN KEY (`orderId`) REFERENCES `orders`(`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Step 4: Verify
SELECT 'Tables recreated successfully!' AS status;
SHOW TABLES LIKE 'referrals';
SHOW TABLES LIKE 'referral_rewards';

