import { getDb } from "../db.ts";
import { users } from "../../drizzle/schema.ts";

export type NotificationType =
  | "daily_bonus"
  | "tournament_start"
  | "achievement_unlocked"
  | "vip_tier_upgrade"
  | "referral_success"
  | "seasonal_event"
  | "game_recommendation"
  | "re_engagement";

export interface PushNotification {
  userId: number;
  type: NotificationType;
  title: string;
  body: string;
  data?: Record<string, string>;
  sentAt?: Date;
  read?: boolean;
}

const NOTIFICATION_TEMPLATES: Record<NotificationType, (data?: any) => { title: string; body: string }> = {
  daily_bonus: (data) => ({
    title: "🎁 Daily Bonus Available",
    body: `Claim your ${data?.amount || 100} GC bonus now!`,
  }),
  tournament_start: (data) => ({
    title: "🏆 Tournament Starting",
    body: `${data?.name || "New tournament"} starts in 1 hour. Join now!`,
  }),
  achievement_unlocked: (data) => ({
    title: "🏅 Achievement Unlocked",
    body: `You've earned the "${data?.name || "Achievement"}" badge!`,
  }),
  vip_tier_upgrade: (data) => ({
    title: "👑 VIP Tier Upgrade",
    body: `Congratulations! You're now ${data?.tier || "VIP"}. Enjoy new perks!`,
  }),
  referral_success: (data) => ({
    title: "🎉 Referral Successful",
    body: `Your friend joined! You earned ${data?.reward || "1 SC"}.`,
  }),
  seasonal_event: (data) => ({
    title: "🎊 Seasonal Event",
    body: `${data?.name || "New event"} is live! Earn exclusive cosmetics.`,
  }),
  game_recommendation: (data) => ({
    title: "🎰 Recommended for You",
    body: `Try ${data?.gameName || "this game"} - you might love it!`,
  }),
  re_engagement: (data) => ({
    title: "👋 We Miss You",
    body: `Come back and claim your ${data?.bonus || "bonus"} bonus!`,
  }),
};

export async function sendPushNotification(
  userId: number,
  type: NotificationType,
  data?: Record<string, string>
): Promise<{ success: boolean; messageId?: string; error?: string }> {
  try {
    const template = NOTIFICATION_TEMPLATES[type];
    if (!template) {
      return { success: false, error: "Unknown notification type" };
    }

    const { title, body } = template(data);

    // In production, this would send to a push notification service
    // (Firebase Cloud Messaging, OneSignal, etc.)
    console.log(`[PUSH] User ${userId}: ${title} - ${body}`);

    return {
      success: true,
      messageId: `push_${Date.now()}`,
    };
  } catch (error) {
    return {
      success: false,
      error: error instanceof Error ? error.message : "Unknown error",
    };
  }
}

export async function sendBatchPushNotifications(
  userIds: number[],
  type: NotificationType,
  data?: Record<string, string>
): Promise<{
  sent: number;
  failed: number;
  errors: string[];
}> {
  let sent = 0;
  let failed = 0;
  const errors: string[] = [];

  for (const userId of userIds) {
    const result = await sendPushNotification(userId, type, data);
    if (result.success) {
      sent++;
    } else {
      failed++;
      errors.push(`User ${userId}: ${result.error}`);
    }
  }

  return { sent, failed, errors };
}

export async function sendDailyBonusNotifications(): Promise<{
  sent: number;
  failed: number;
}> {
  const db = await getDb();
  if (!db) return { sent: 0, failed: 0 };

  const allUsers = await db.select().from(users);
  const result = await sendBatchPushNotifications(
    allUsers.map((u) => u.id),
    "daily_bonus",
    { amount: "5000" }
  );

  return { sent: result.sent, failed: result.failed };
}

export async function sendTournamentNotifications(
  tournamentName: string,
  userIds: number[]
): Promise<{ sent: number; failed: number }> {
  const result = await sendBatchPushNotifications(
    userIds,
    "tournament_start",
    { name: tournamentName }
  );

  return { sent: result.sent, failed: result.failed };
}

export async function sendAchievementNotification(
  userId: number,
  achievementName: string
): Promise<{ success: boolean }> {
  const result = await sendPushNotification(userId, "achievement_unlocked", {
    name: achievementName,
  });

  return { success: result.success };
}

export async function sendVIPTierNotification(
  userId: number,
  tier: string
): Promise<{ success: boolean }> {
  const result = await sendPushNotification(userId, "vip_tier_upgrade", {
    tier,
  });

  return { success: result.success };
}

export async function sendReferralNotification(
  userId: number,
  reward: string
): Promise<{ success: boolean }> {
  const result = await sendPushNotification(userId, "referral_success", {
    reward,
  });

  return { success: result.success };
}

export async function sendReEngagementNotifications(
  daysSinceLastLogin: number = 7
): Promise<{ sent: number; failed: number }> {
  const db = await getDb();
  if (!db) return { sent: 0, failed: 0 };

  // Get users who haven't logged in for N days
  const allUsers = await db.select().from(users);
  const inactiveUsers = allUsers.filter((user) => {
    const lastLogin = user.lastLoginAt ? new Date(user.lastLoginAt) : null;
    if (!lastLogin) return true;

    const daysSinceLogin = Math.floor(
      (Date.now() - lastLogin.getTime()) / (1000 * 60 * 60 * 24)
    );
    return daysSinceLogin >= daysSinceLastLogin;
  });

  const result = await sendBatchPushNotifications(
    inactiveUsers.map((u) => u.id),
    "re_engagement",
    { bonus: "5000 GC" }
  );

  return { sent: result.sent, failed: result.failed };
}
