-- Token System Database Tables
-- Complete monetization system with Rainforest Pay integration

-- Token purchases table
CREATE TABLE IF NOT EXISTS token_purchases (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    usd_amount DECIMAL(10,2) NOT NULL,
    token_amount INT NOT NULL,
    exchange_rate DECIMAL(10,4) NOT NULL,
    payment_id VARCHAR(255) NULL,
    status ENUM('pending', 'completed', 'failed', 'cancelled') DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    
    INDEX idx_user_id (user_id),
    INDEX idx_payment_id (payment_id),
    INDEX idx_status (status),
    INDEX idx_created_at (created_at)
);

-- Token redemptions table
CREATE TABLE IF NOT EXISTS token_redemptions (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    token_amount INT NOT NULL,
    gross_usd DECIMAL(10,2) NOT NULL,
    platform_fee DECIMAL(10,2) NOT NULL,
    net_usd DECIMAL(10,2) NOT NULL,
    redemption_method ENUM('bank_transfer', 'mobile_money', 'paypal') NOT NULL,
    payout_id INT NULL,
    status ENUM('pending', 'processing', 'completed', 'failed') DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    completed_at TIMESTAMP NULL,
    failed_at TIMESTAMP NULL,
    
    INDEX idx_user_id (user_id),
    INDEX idx_payout_id (payout_id),
    INDEX idx_status (status),
    INDEX idx_created_at (created_at)
);

-- Token payouts table (Rainforest Pay integration)
CREATE TABLE IF NOT EXISTS token_payouts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    redemption_id INT NOT NULL,
    user_id INT NOT NULL,
    usd_amount DECIMAL(10,2) NOT NULL,
    rainforest_payout_id VARCHAR(255) NULL,
    status ENUM('pending', 'processing', 'completed', 'failed') DEFAULT 'pending',
    failure_reason TEXT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    completed_at TIMESTAMP NULL,
    failed_at TIMESTAMP NULL,
    
    INDEX idx_redemption_id (redemption_id),
    INDEX idx_user_id (user_id),
    INDEX idx_rainforest_payout_id (rainforest_payout_id),
    INDEX idx_status (status),
    
    FOREIGN KEY (redemption_id) REFERENCES token_redemptions(id) ON DELETE CASCADE
);

-- User payout settings table
CREATE TABLE IF NOT EXISTS user_payout_settings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL UNIQUE,
    payout_method ENUM('bank_transfer', 'mobile_money', 'paypal') NOT NULL,
    payout_details JSON NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    
    INDEX idx_user_id (user_id),
    INDEX idx_payout_method (payout_method)
);

-- Token packages configuration (stored in db_settings)
INSERT INTO db_settings (setting_key, setting_value, setting_description) VALUES
('token_package_small', '{"tokens": 100, "bonus": 10, "usd": 10, "popular": false}', 'Small token package'),
('token_package_medium', '{"tokens": 500, "bonus": 75, "usd": 50, "popular": true}', 'Medium token package (most popular)'),
('token_package_large', '{"tokens": 1000, "bonus": 200, "usd": 100, "popular": false}', 'Large token package'),
('token_package_mega', '{"tokens": 2500, "bonus": 750, "usd": 250, "popular": false}', 'Mega token package')
ON DUPLICATE KEY UPDATE 
setting_value = VALUES(setting_value),
setting_description = VALUES(setting_description);

-- Update token settings with monetization features
UPDATE db_settings SET setting_value = JSON_SET(
    COALESCE(setting_value, '{}'),
    '$.min_purchase', 5,
    '$.max_purchase', 1000,
    '$.min_redemption', 100,
    '$.platform_fee_rate', 0.05,
    '$.exchange_rate', 0.01
) WHERE setting_key = 'token_settings';

-- Create indexes for better performance
CREATE INDEX IF NOT EXISTS idx_token_transactions_user_type ON token_transactions(user_id, transaction_type);
CREATE INDEX IF NOT EXISTS idx_token_transactions_created ON token_transactions(created_at);

-- Add donation balance column to users table if not exists
ALTER TABLE db_accountuser 
ADD COLUMN IF NOT EXISTS donation_balance DECIMAL(10,2) DEFAULT 0.00,
ADD COLUMN IF NOT EXISTS token_balance INT DEFAULT 0;

-- Create view for user token balances
CREATE OR REPLACE VIEW user_token_balances AS
SELECT 
    u.usr_id as user_id,
    u.usr_user as username,
    COALESCE(SUM(CASE WHEN tt.transaction_type IN ('purchase', 'gift_received', 'refund') THEN tt.amount ELSE 0 END), 0) -
    COALESCE(SUM(CASE WHEN tt.transaction_type IN ('gift_sent', 'redemption', 'spend') THEN tt.amount ELSE 0 END), 0) as token_balance,
    COUNT(CASE WHEN tt.transaction_type = 'purchase' THEN 1 END) as total_purchases,
    COALESCE(SUM(CASE WHEN tt.transaction_type = 'purchase' THEN tt.amount END), 0) as total_purchased_tokens,
    COUNT(CASE WHEN tt.transaction_type = 'redemption' THEN 1 END) as total_redemptions,
    COALESCE(SUM(CASE WHEN tt.transaction_type = 'redemption' THEN tt.amount END), 0) as total_redeemed_tokens
FROM db_accountuser u
LEFT JOIN token_transactions tt ON u.usr_id = tt.user_id
GROUP BY u.usr_id, u.usr_user;

-- Create view for token purchase analytics
CREATE OR REPLACE VIEW token_purchase_analytics AS
SELECT 
    DATE(tp.created_at) as purchase_date,
    COUNT(*) as total_purchases,
    SUM(tp.usd_amount) as total_usd,
    SUM(tp.token_amount) as total_tokens,
    AVG(tp.usd_amount) as avg_purchase_amount,
    COUNT(DISTINCT tp.user_id) as unique_buyers
FROM token_purchases tp
WHERE tp.status = 'completed'
GROUP BY DATE(tp.created_at)
ORDER BY purchase_date DESC;

-- Create view for token redemption analytics
CREATE OR REPLACE VIEW token_redemption_analytics AS
SELECT 
    DATE(tr.created_at) as redemption_date,
    COUNT(*) as total_redemptions,
    SUM(tr.token_amount) as total_tokens_redeemed,
    SUM(tr.gross_usd) as total_gross_usd,
    SUM(tr.platform_fee) as total_platform_fees,
    SUM(tr.net_usd) as total_net_usd,
    AVG(tr.token_amount) as avg_redemption_amount,
    COUNT(DISTINCT tr.user_id) as unique_redeemers
FROM token_redemptions tr
WHERE tr.status = 'completed'
GROUP BY DATE(tr.created_at)
ORDER BY redemption_date DESC;

-- Sample data for testing (remove in production)
-- INSERT INTO token_purchases (user_id, usd_amount, token_amount, exchange_rate, status) VALUES
-- (1, 10.00, 110, 0.01, 'completed'),
-- (2, 50.00, 575, 0.01, 'completed'),
-- (3, 100.00, 1200, 0.01, 'pending');

COMMIT;