-- AlterTable
ALTER TABLE `users` ADD COLUMN `referral_code` VARCHAR(32) NULL,
    ADD COLUMN `referred_by_id` CHAR(36) NULL;

-- AlterTable
ALTER TABLE `auth_otps` ADD COLUMN `referral_code` VARCHAR(32) NULL,
    ADD COLUMN `referrer_id` CHAR(36) NULL;

-- CreateTable
CREATE TABLE `referral_settings` (
    `id` VARCHAR(32) NOT NULL DEFAULT 'default',
    `enabled` BOOLEAN NOT NULL DEFAULT true,
    `planter_bonus_amount` DECIMAL(12, 2) NOT NULL DEFAULT 25.00,
    `donor_bonus_amount` DECIMAL(12, 2) NOT NULL DEFAULT 25.00,
    `currency` CHAR(3) NOT NULL DEFAULT 'INR',
    `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `updated_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),

    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- CreateTable
CREATE TABLE `referral_rewards` (
    `id` CHAR(36) NOT NULL,
    `referrer_id` CHAR(36) NOT NULL,
    `referred_user_id` CHAR(36) NOT NULL,
    `referral_code` VARCHAR(32) NOT NULL,
    `referrer_role` ENUM('PLANTER', 'DONOR', 'ADMIN') NOT NULL,
    `amount` DECIMAL(12, 2) NOT NULL,
    `currency` CHAR(3) NOT NULL DEFAULT 'INR',
    `status` ENUM('PAID', 'REJECTED') NOT NULL DEFAULT 'PAID',
    `wallet_transaction_id` CHAR(36) NULL,
    `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `credited_at` DATETIME(3) NULL,

    UNIQUE INDEX `referral_rewards_referred_user_id_key`(`referred_user_id`),
    UNIQUE INDEX `referral_rewards_wallet_transaction_id_key`(`wallet_transaction_id`),
    INDEX `referral_rewards_referrer_id_idx`(`referrer_id`),
    INDEX `referral_rewards_referral_code_idx`(`referral_code`),
    INDEX `referral_rewards_status_idx`(`status`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- Seed singleton settings row
INSERT INTO `referral_settings` (`id`, `enabled`, `planter_bonus_amount`, `donor_bonus_amount`, `currency`)
VALUES ('default', true, 25.00, 25.00, 'INR')
ON DUPLICATE KEY UPDATE `id` = `id`;

-- CreateIndex
CREATE UNIQUE INDEX `users_referral_code_key` ON `users`(`referral_code`);

-- CreateIndex
CREATE INDEX `users_referred_by_id_idx` ON `users`(`referred_by_id`);

-- AddForeignKey
ALTER TABLE `users` ADD CONSTRAINT `users_referred_by_id_fkey` FOREIGN KEY (`referred_by_id`) REFERENCES `users`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `referral_rewards` ADD CONSTRAINT `referral_rewards_referrer_id_fkey` FOREIGN KEY (`referrer_id`) REFERENCES `users`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `referral_rewards` ADD CONSTRAINT `referral_rewards_referred_user_id_fkey` FOREIGN KEY (`referred_user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `referral_rewards` ADD CONSTRAINT `referral_rewards_wallet_transaction_id_fkey` FOREIGN KEY (`wallet_transaction_id`) REFERENCES `wallet_transactions`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
