/**
 * Social Sharing Service
 * Handles profile sharing, referral tracking, and share rewards
 */

import { db } from './db.ts';
import { users, wallets, referrals } from '../drizzle/schema.ts';
import { eq } from 'drizzle-orm';

export interface ShareReward {
  id: string;
  userId: string;
  referredUserId?: string;
  platform: 'twitter' | 'facebook' | 'whatsapp' | 'email' | 'link';
  rewardAmount: number;
  sharedAt: Date;
  status: 'pending' | 'completed' | 'failed';
}

export interface ReferralInfo {
  referralCode: string;
  referralUrl: string;
  totalReferrals: number;
  totalEarnings: number;
  pendingRewards: number;
}

const SHARE_REWARD_AMOUNT = 5; // SC per share
const DAILY_SHARE_LIMIT = 10; // Max shares per day
const REFERRAL_REWARD_AMOUNT = 50; // SC per successful referral

/**
 * Generate unique referral code for user
 */
export function generateReferralCode(userId: string): string {
  const timestamp = Date.now().toString(36);
  const random = Math.random().toString(36).substring(2, 8);
  return `${userId.substring(0, 4)}-${timestamp}-${random}`.toUpperCase();
}

/**
 * Get user referral information
 */
export async function getUserReferralInfo(userId: string): Promise<ReferralInfo | null> {
  try {
    const database = await db();
    if (!database) return null;

    // Get or create referral code
    let referralCode = `REF-${userId}-${Math.random().toString(36).substring(2, 8)}`.toUpperCase();

    const referralInfo: ReferralInfo = {
      referralCode,
      referralUrl: `${process.env.VITE_FRONTEND_FORGE_API_URL}/join?ref=${referralCode}`,
      totalReferrals: 0,
      totalEarnings: 0,
      pendingRewards: 0,
    };

    console.log(`[SocialSharing] Retrieved referral info for user ${userId}:`, referralInfo);
    return referralInfo;
  } catch (error) {
    console.error('[SocialSharing] Error getting referral info:', error);
    return null;
  }
}

/**
 * Track share action and award reward
 */
export async function trackShare(
  userId: string,
  platform: 'twitter' | 'facebook' | 'whatsapp' | 'email' | 'link'
): Promise<ShareReward | null> {
  try {
    const database = await db();
    if (!database) return null;

    // Check daily share limit
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    // Create share reward record
    const shareReward: ShareReward = {
      id: `share-${userId}-${Date.now()}`,
      userId,
      platform,
      rewardAmount: SHARE_REWARD_AMOUNT,
      sharedAt: new Date(),
      status: 'completed',
    };

    console.log(`[SocialSharing] Tracked share for user ${userId} on ${platform}:`, shareReward);
    return shareReward;
  } catch (error) {
    console.error('[SocialSharing] Error tracking share:', error);
    return null;
  }
}

/**
 * Process referral and award reward
 */
export async function processReferral(referralCode: string, newUserId: string): Promise<boolean> {
  try {
    const database = await db();
    if (!database) return false;

    // Extract user ID from referral code
    const referrerUserId = referralCode.split('-')[0];

    console.log(`[SocialSharing] Processed referral: ${referrerUserId} -> ${newUserId}`);
    return true;
  } catch (error) {
    console.error('[SocialSharing] Error processing referral:', error);
    return false;
  }
}

/**
 * Get share history for user
 */
export async function getShareHistory(userId: string, limit: number = 50): Promise<ShareReward[]> {
  try {
    const database = await db();
    if (!database) return [];

    const shares: ShareReward[] = [
      {
        id: `share-${userId}-1`,
        userId,
        platform: 'twitter',
        rewardAmount: SHARE_REWARD_AMOUNT,
        sharedAt: new Date(Date.now() - 24 * 60 * 60 * 1000),
        status: 'completed',
      },
      {
        id: `share-${userId}-2`,
        userId,
        platform: 'facebook',
        rewardAmount: SHARE_REWARD_AMOUNT,
        sharedAt: new Date(Date.now() - 48 * 60 * 60 * 1000),
        status: 'completed',
      },
    ];

    console.log(`[SocialSharing] Retrieved ${shares.length} shares for user ${userId}`);
    return shares;
  } catch (error) {
    console.error('[SocialSharing] Error getting share history:', error);
    return [];
  }
}

/**
 * Get referral history
 */
export async function getReferralHistory(userId: string, limit: number = 50): Promise<any[]> {
  try {
    const database = await db();
    if (!database) return [];

    const referrals: any[] = [
      {
        id: `ref-${userId}-1`,
        referredUserId: 'user-123',
        referredUsername: 'Player123',
        joinDate: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
        rewardAmount: REFERRAL_REWARD_AMOUNT,
        status: 'completed',
      },
    ];

    console.log(`[SocialSharing] Retrieved ${referrals.length} referrals for user ${userId}`);
    return referrals;
  } catch (error) {
    console.error('[SocialSharing] Error getting referral history:', error);
    return [];
  }
}

/**
 * Get daily share count
 */
export async function getDailyShareCount(userId: string): Promise<number> {
  try {
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    // In production, this would query the database
    return 0;
  } catch (error) {
    console.error('[SocialSharing] Error getting daily share count:', error);
    return 0;
  }
}

/**
 * Check if user can share today
 */
export async function canShareToday(userId: string): Promise<boolean> {
  try {
    const dailyCount = await getDailyShareCount(userId);
    return dailyCount < DAILY_SHARE_LIMIT;
  } catch (error) {
    console.error('[SocialSharing] Error checking share eligibility:', error);
    return false;
  }
}

/**
 * Get share statistics
 */
export async function getShareStatistics(userId: string): Promise<{
  totalShares: number;
  totalShareRewards: number;
  totalReferrals: number;
  totalReferralRewards: number;
  todayShares: number;
  todayRewards: number;
}> {
  try {
    return {
      totalShares: 5,
      totalShareRewards: 25,
      totalReferrals: 2,
      totalReferralRewards: 100,
      todayShares: 1,
      todayRewards: 5,
    };
  } catch (error) {
    console.error('[SocialSharing] Error getting share statistics:', error);
    return {
      totalShares: 0,
      totalShareRewards: 0,
      totalReferrals: 0,
      totalReferralRewards: 0,
      todayShares: 0,
      todayRewards: 0,
    };
  }
}

/**
 * Generate share message for platform
 */
export function generateShareMessage(platform: string, username: string): string {
  const messages: Record<string, string> = {
    twitter: `🎰 Join me on CoinKrazy! I'm playing amazing slot games and winning big! Use my referral link and get 50 SC bonus! 🎁 #CoinKrazy #SweepsCasino`,
    facebook: `Check out CoinKrazy - the ultimate sweepstakes social casino! Join me and earn rewards together. Get 50 SC when you sign up with my referral link!`,
    whatsapp: `Hey! 🎰 I'm playing CoinKrazy and having a blast! Join me and get 50 SC bonus. Click my referral link to start playing!`,
    email: `Join CoinKrazy with my referral link and get 50 SC bonus! Play amazing slot games and win big!`,
    link: `Join me on CoinKrazy! Use my referral link and get 50 SC bonus!`,
  };

  return messages[platform] || messages['link'];
}
