import { initDb } from "@/lib/db";
import { Op } from "sequelize";

export interface NotificationItem {
  id: string;
  action: string;
  title: string;
  description: string;
  icon: "survey" | "response" | "publish" | "close" | "profile" | "billing" | "info";
  createdAt: Date;
  metadata: Record<string, unknown> | null;
}

const ACTION_MAP: Record<
  string,
  {
    title: string;
    description: (m: Record<string, unknown>) => string;
    icon:
      | NotificationItem["icon"]
      | ((m: Record<string, unknown>) => NotificationItem["icon"]);
  }
> = {
  "survey.created": {
    title: "Survey Created",
    description: (m) => `New survey created${m.title ? `: "${m.title}"` : ""}`,
    icon: "survey",
  },
  "survey.published": {
    title: "Survey Published",
    description: () => "Survey is now live and collecting responses",
    icon: "publish",
  },
  "survey.status_changed": {
    title: "Survey Status Changed",
    description: (m) => `Survey status changed to ${String(m.status ?? "unknown")}`,
    icon: (m: Record<string, unknown>) =>
      m.status === "active" ? "publish" : m.status === "closed" ? "close" : "survey",
  },
  "survey.updated": {
    title: "Survey Updated",
    description: () => "Survey settings were updated",
    icon: "survey",
  },
  "survey.duplicated": {
    title: "Survey Duplicated",
    description: () => "A copy of the survey was created",
    icon: "survey",
  },
  "survey.deleted": {
    title: "Survey Deleted",
    description: (m) => `Survey "${String(m.title ?? "")}" was permanently deleted`,
    icon: "close",
  },
  "user.profile_updated": {
    title: "Profile Updated",
    description: () => "Your profile information was updated",
    icon: "profile",
  },
};

function resolveIcon(
  entry: { icon: NotificationItem["icon"] | ((m: Record<string, unknown>) => NotificationItem["icon"]) },
  meta: Record<string, unknown>
): NotificationItem["icon"] {
  return typeof entry.icon === "function" ? entry.icon(meta) : entry.icon;
}

export async function getWorkspaceNotifications(
  workspaceId: string,
  limit = 20
): Promise<NotificationItem[]> {
  const { AuditLog } = initDb();

  const logs = await AuditLog.findAll({
    where: {
      workspaceId,
      action: { [Op.in]: Object.keys(ACTION_MAP) },
    },
    order: [["createdAt", "DESC"]],
    limit,
  });

  return logs.map((log) => {
    const meta = (log.metadata ?? {}) as Record<string, unknown>;
    const mapping = ACTION_MAP[log.action];

    if (!mapping) {
      return {
        id: log.id,
        action: log.action,
        title: log.action,
        description: "",
        icon: "info" as const,
        createdAt: log.createdAt,
        metadata: log.metadata,
      };
    }

    return {
      id: log.id,
      action: log.action,
      title: mapping.title,
      description: mapping.description(meta),
      icon: resolveIcon(mapping, meta),
      createdAt: log.createdAt,
      metadata: log.metadata,
    };
  });
}
