import { invokeLLM } from "../_core/llm.ts";

export interface PushNotification {
  id: string;
  userId: number;
  title: string;
  body: string;
  icon?: string;
  badge?: string;
  tag?: string;
  data?: Record<string, string>;
  sent: boolean;
  sentAt?: Date;
  read: boolean;
  readAt?: Date;
  createdAt: Date;
}

export interface DeviceRegistration {
  id: string;
  userId: number;
  deviceToken: string;
  platform: "web" | "ios" | "android";
  isActive: boolean;
  lastSeen: Date;
  createdAt: Date;
}

export interface PushCampaign {
  id: string;
  title: string;
  body: string;
  targetSegment: "all" | "vip" | "active_players" | "inactive_players" | "high_spenders";
  icon?: string;
  data?: Record<string, string>;
  scheduledTime?: Date;
  status: "draft" | "scheduled" | "sent" | "failed";
  recipientCount: number;
  sentCount: number;
  readRate: number;
  createdAt: Date;
  updatedAt: Date;
}

export async function registerDevice(userId: number, deviceToken: string, platform: "web" | "ios" | "android"): Promise<DeviceRegistration> {
  const id = `device_${userId}_${Date.now()}`;
  const now = new Date();

  const registration: DeviceRegistration = {
    id,
    userId,
    deviceToken,
    platform,
    isActive: true,
    lastSeen: now,
    createdAt: now,
  };

  console.log("[Push Notifications] Device registered:", registration);

  return registration;
}

export async function sendPushNotification(userId: number, notification: Omit<PushNotification, "id" | "sent" | "read" | "createdAt" | "sentAt" | "readAt">): Promise<PushNotification> {
  const id = `notif_${userId}_${Date.now()}`;
  const now = new Date();

  const pushNotif: PushNotification = {
    ...notification,
    id,
    sent: true,
    sentAt: now,
    read: false,
    createdAt: now,
  };

  console.log("[Push Notifications] Notification sent:", pushNotif);

  return pushNotif;
}

export async function sendPushCampaign(campaign: Omit<PushCampaign, "id" | "createdAt" | "updatedAt" | "sentCount" | "readRate">): Promise<PushCampaign> {
  const id = `campaign_${Date.now()}`;
  const now = new Date();

  const pushCampaign: PushCampaign = {
    ...campaign,
    id,
    sentCount: 0,
    readRate: 0,
    createdAt: now,
    updatedAt: now,
  };

  console.log("[Push Notifications] Campaign created:", pushCampaign);

  return pushCampaign;
}

export async function markNotificationAsRead(notificationId: string): Promise<void> {
  console.log(`[Push Notifications] Notification ${notificationId} marked as read`);
}

export async function getDeviceTokensForSegment(segment: string): Promise<Array<{ userId: number; deviceToken: string; platform: string }>> {
  // Mock implementation - would query database for real device tokens
  const mockTokens = [
    { userId: 1, deviceToken: "token_1", platform: "web" },
    { userId: 2, deviceToken: "token_2", platform: "ios" },
    { userId: 3, deviceToken: "token_3", platform: "android" },
  ];

  return mockTokens;
}

export async function generatePushNotificationContent(prompt: string): Promise<{ title: string; body: string }> {
  const response = await invokeLLM({
    messages: [
      {
        role: "system",
        content: "You are an expert push notification copywriter for a social casino. Create concise, engaging push notifications that drive immediate action.",
      },
      {
        role: "user",
        content: prompt,
      },
    ],
    response_format: {
      type: "json_schema",
      json_schema: {
        name: "push_notification",
        strict: true,
        schema: {
          type: "object",
          properties: {
            title: { type: "string", description: "Push notification title (max 50 chars)" },
            body: { type: "string", description: "Push notification body (max 150 chars)" },
          },
          required: ["title", "body"],
          additionalProperties: false,
        },
      },
    },
  });

  const content = JSON.parse(response.choices[0]?.message.content || '{"title":"","body":""}');
  return content;
}

export async function schedulePushCampaign(campaignId: string, scheduledTime: Date): Promise<void> {
  console.log(`[Push Notifications] Campaign ${campaignId} scheduled for ${scheduledTime.toISOString()}`);
}

export async function getCampaignStats(campaignId: string): Promise<{ sent: number; read: number; clicked: number }> {
  // Mock implementation
  return {
    sent: 5000,
    read: 3250,
    clicked: 850,
  };
}

export async function deactivateDevice(deviceId: string): Promise<void> {
  console.log(`[Push Notifications] Device ${deviceId} deactivated`);
}

export async function updateDeviceLastSeen(deviceId: string): Promise<void> {
  console.log(`[Push Notifications] Device ${deviceId} last seen updated`);
}
