// @ts-nocheck — Legacy notification service. Superseded by notification-service.ts.
import { prisma } from "@/lib/prisma";

export type NotifCategory = "login" | "system" | "security" | "integration" | "task" | "billing" | "workspace";

/**
 * List notifications for a user.
 */
export async function getNotifications(
  userId: string,
  filters?: { category?: NotifCategory; unreadOnly?: boolean; limit?: number }
) {
  return prisma.notification.findMany({
    where: {
      userId,
      ...(filters?.category ? { category: filters.category } : {}),
      ...(filters?.unreadOnly ? { status: "unread" } : { status: { not: "dismissed" } }),
    },
    orderBy: { createdAt: "desc" },
    take: filters?.limit ?? 50,
  });
}

/**
 * Get unread count for a user.
 */
export async function getUnreadCount(userId: string): Promise<number> {
  return prisma.notification.count({
    where: { userId, status: "unread" },
  });
}

/**
 * Mark one notification as read.
 */
export async function markAsRead(notificationId: string) {
  return prisma.notification.update({
    where: { id: notificationId },
    data: { status: "read", readAt: new Date() },
  });
}

/**
 * Mark all unread notifications as read for a user.
 */
export async function markAllAsRead(userId: string) {
  return prisma.notification.updateMany({
    where: { userId, status: "unread" },
    data: { status: "read", readAt: new Date() },
  });
}

/**
 * Dismiss a notification.
 */
export async function dismissNotification(notificationId: string) {
  return prisma.notification.update({
    where: { id: notificationId },
    data: { status: "dismissed", dismissedAt: new Date() },
  });
}

/**
 * Create a notification.
 */
export async function createNotification(data: {
  userId: string;
  category: NotifCategory;
  title: string;
  message: string;
  actionUrl?: string;
  orgId?: string;
  brandId?: string;
  metadata?: Record<string, unknown>;
}) {
  return prisma.notification.create({
    data: {
      userId: data.userId,
      category: data.category,
      title: data.title,
      message: data.message,
      actionUrl: data.actionUrl,
      orgId: data.orgId,
      brandId: data.brandId,
      metadata: data.metadata ? JSON.parse(JSON.stringify(data.metadata)) : {},
    },
  });
}

/**
 * Seed mock notifications for a user.
 */
export async function seedNotificationsForUser(userId: string, orgId?: string) {
  const mocks: Array<{
    category: NotifCategory;
    title: string;
    message: string;
    actionUrl?: string;
    minutesAgo: number;
    read: boolean;
  }> = [
    { category: "security",    title: "New login detected",             message: "Chrome on macOS — New York, NY",                          actionUrl: "/settings",           minutesAgo: 2,     read: false },
    { category: "system",      title: "Crawl completed",                message: "1,248 pages scanned for acme.com in 4m 22s",              actionUrl: "/technical-audit",    minutesAgo: 18,    read: false },
    { category: "integration", title: "Google Search Console synced",   message: "1,248 pages — 38 keywords tracked. Next sync in 6 hours.",actionUrl: "/dashboard",          minutesAgo: 30,    read: false },
    { category: "task",        title: "Task assigned to you",           message: "\"Fix meta descriptions on 14 pages\" — due Apr 2",       actionUrl: "/execution-hub",      minutesAgo: 45,    read: false },
    { category: "integration", title: "HubSpot connection failed",      message: "API token expired. Reconnect to resume CRM sync.",         actionUrl: "/integrations",       minutesAgo: 60,    read: false },
    { category: "task",        title: "Task completed by Alex",         message: "\"Optimize hero images\" marked as done",                  actionUrl: "/execution-hub",      minutesAgo: 120,   read: true },
    { category: "integration", title: "Google Analytics connected",     message: "GA4 property linked. Historical data importing.",           actionUrl: "/integrations",       minutesAgo: 180,   read: true },
    { category: "security",    title: "Password changed",               message: "Account password updated successfully",                    minutesAgo: 300,                                    read: true },
    { category: "task",        title: "3 tasks overdue",                message: "\"Fix NAP\", \"Add FAQ schema\", \"HTTP mixed content\"",  actionUrl: "/execution-hub",      minutesAgo: 360,   read: true },
    { category: "billing",     title: "Invoice paid",                   message: "Pro plan — $99/mo charged to Visa •••• 4242",              actionUrl: "/settings",           minutesAgo: 1440,  read: true },
    { category: "workspace",   title: "New brand added",                message: "Beacon Health added to Mazzei Agency workspace",           actionUrl: "/brands-hub",         minutesAgo: 1440,  read: true },
    { category: "billing",     title: "Plan upgraded to Pro",           message: "Unlocked: unlimited brands, API access, priority support", actionUrl: "/settings",           minutesAgo: 2880,  read: true },
    { category: "workspace",   title: "Team member joined",             message: "alex@company.com accepted invite as Editor",               actionUrl: "/settings",           minutesAgo: 2880,  read: true },
    { category: "system",      title: "Report generated",               message: "Monthly SEO report ready for download",                    actionUrl: "/report-studio",      minutesAgo: 4320,  read: true },
    { category: "billing",     title: "Usage approaching limit",        message: "85% of crawl quota used (8,500 / 10,000 pages)",           actionUrl: "/settings",           minutesAgo: 4320,  read: true },
    { category: "workspace",   title: "Brand settings updated",         message: "Acme Corp — industry changed to Technology",               actionUrl: "/settings",           minutesAgo: 5760,  read: true },
    { category: "system",      title: "Scheduled maintenance",          message: "Platform update tonight 2-3 AM EST. No downtime expected.",                                  minutesAgo: 5760,  read: true },
    { category: "task",        title: "Page launched from task",        message: "\"AI Tools Guide\" published → tracking started",           actionUrl: "/page-launch-tracker",minutesAgo: 7200,  read: true },
  ];

  let created = 0;
  for (const m of mocks) {
    const createdAt = new Date(Date.now() - m.minutesAgo * 60000);
    await prisma.notification.create({
      data: {
        userId,
        category: m.category,
        title: m.title,
        message: m.message,
        actionUrl: m.actionUrl,
        orgId,
        status: m.read ? "read" : "unread",
        readAt: m.read ? createdAt : null,
        createdAt,
      },
    });
    created++;
  }
  return { created };
}
