/**
 * System Alerts helper
 *
 * Records operational/security alerts into the system_messages table so they
 * surface inside the staff dashboard. Designed to be lightweight and to avoid
 * alert storms with a simple cooldown.
 */
import { prisma } from './db';
import { systemMessagesAdapter } from './adapters/system';
import { createId } from '@paralleldrive/cuid2';
import { logger } from './logger';

type Severity = 'info' | 'warning' | 'error';

interface RecordAlertOptions {
  title: string;
  message: string;
  severity?: Severity;
  source?: string;
  environment?: string;
  expiresInMinutes?: number;
  cooldownKey?: string;
  cooldownMinutes?: number;
}

const alertCooldowns = new Map<string, number>();
let cachedSystemUserId: string | null = null;

function getEnvLabel(): string {
  return (
    process.env.APP_ENV ||
    process.env.VERCEL_ENV ||
    process.env.NODE_ENV ||
    'unknown'
  );
}

function isOnCooldown(key: string, windowMinutes: number): boolean {
  if (!key) return false;
  const now = Date.now();
  const existing = alertCooldowns.get(key);
  if (!existing) return false;
  return now - existing < windowMinutes * 60 * 1000;
}

function setCooldown(key: string): void {
  if (!key) return;
  alertCooldowns.set(key, Date.now());
}

export async function recordSystemAlert({
  title,
  message,
  severity = 'warning',
  source,
  environment,
  expiresInMinutes = 60,
  cooldownKey,
  cooldownMinutes = 10,
}: RecordAlertOptions): Promise<void> {
  try {
    const cooldownId = cooldownKey || `${source || 'generic'}:${title}:${severity}`;
    if (isOnCooldown(cooldownId, cooldownMinutes)) {
      return;
    }

    const now = new Date();
    const expiresAt = expiresInMinutes ? new Date(now.getTime() + expiresInMinutes * 60 * 1000) : null;

    if (!cachedSystemUserId) {
      const fallbackUser = await prisma.users.findFirst({
        where: { role: { in: ['SUPER_ADMIN', 'ADMIN'] } },
        select: { id: true },
      });

      if (!fallbackUser) {
        logger.warn('No admin user found to attach system alert');
        return;
      }

      cachedSystemUserId = fallbackUser.id;
    }

    await systemMessagesAdapter.create({
      data: {
        id: createId(),
        type: severity,
        title: title.slice(0, 120),
        message: `[${environment || getEnvLabel()}]${source ? ` [${source}]` : ''} ${message}`.trim(),
        isActive: true,
        createdAt: now,
        updatedAt: now,
        expiresAt,
        createdBy: cachedSystemUserId,
      },
    });

    setCooldown(cooldownId);
  } catch (error) {
    logger.error('Failed to record system alert', {
      error: error instanceof Error ? error.message : String(error),
      title,
      source,
    });
  }
}

export function buildQueueAlertMessage(queue: string, reason: string): string {
  return `Queue ${queue}: ${reason}`;
}

export function buildHealthAlertMessage(endpoint: string, status: string, reason?: string): string {
  return `Health ${endpoint} -> ${status}${reason ? ` (${reason})` : ''}`;
}
