import { readJson, writeJson } from './storage';
import { randomUUID } from 'node:crypto';

export type NotificationType = 'submission' | 'seo_drop' | 'geo_drop';

export type Notification = {
  id: string;
  type: NotificationType;
  title: string;
  message: string;
  link?: string;
  createdAt: string;
  read: boolean;
};

const FILE = 'notifications.json';
const MAX_KEEP = 200;

export function listNotifications(): Notification[] {
  const all = readJson<Notification[]>(FILE, []);
  return [...all].sort((a, b) => b.createdAt.localeCompare(a.createdAt));
}

export function unreadCount(): number {
  return readJson<Notification[]>(FILE, []).filter((n) => !n.read).length;
}

export function addNotification(input: Omit<Notification, 'id' | 'createdAt' | 'read'>): Notification {
  const all = readJson<Notification[]>(FILE, []);
  const entry: Notification = {
    id: randomUUID(),
    createdAt: new Date().toISOString(),
    read: false,
    ...input
  };
  all.push(entry);
  // Keep only the most recent MAX_KEEP
  const sorted = all.sort((a, b) => b.createdAt.localeCompare(a.createdAt)).slice(0, MAX_KEEP);
  writeJson(FILE, sorted);
  return entry;
}

export function markRead(id: string): void {
  const all = readJson<Notification[]>(FILE, []);
  writeJson(FILE, all.map((n) => (n.id === id ? { ...n, read: true } : n)));
}

export function markAllRead(): void {
  const all = readJson<Notification[]>(FILE, []);
  writeJson(FILE, all.map((n) => ({ ...n, read: true })));
}

export function deleteNotification(id: string): void {
  const all = readJson<Notification[]>(FILE, []);
  writeJson(FILE, all.filter((n) => n.id !== id));
}
