import { and, eq } from 'drizzle-orm';

import { db } from '@/lib/db';
import { systemSettings } from '@/lib/db/schema/system';
import { settingKeyForSubject, type TemplateKey } from '@/lib/email/template-catalog';

/**
 * Returns the per-port subject override for a transactional email template,
 * or null if no override is configured.
 *
 * Per-port row wins over global (null portId). String values are returned
 * as-is; non-string values are ignored (treated as no override).
 */
export async function loadSubjectOverride(
  portId: string,
  key: TemplateKey,
): Promise<string | null> {
  const settingKey = settingKeyForSubject(key);
  const rows = await db
    .select({ value: systemSettings.value, portId: systemSettings.portId })
    .from(systemSettings)
    .where(eq(systemSettings.key, settingKey));

  // Prefer per-port row; fall back to global (null portId).
  const portRow = rows.find((r) => r.portId === portId);
  const globalRow = rows.find((r) => r.portId === null);
  const value = portRow?.value ?? globalRow?.value ?? null;
  return typeof value === 'string' && value.trim() ? value : null;
}

/** Synchronous client-side helper for substituting {{token}} placeholders. */
export function applySubjectTokens(
  template: string,
  tokens: Record<string, string | number | undefined>,
): string {
  return template.replace(/\{\{(\w+)\}\}/g, (match, name: string) => {
    const v = tokens[name];
    return v === undefined || v === null ? match : String(v);
  });
}

// Suppress unused-import lint when the helper is not yet referenced from
// every template — every consumer uses `and` once it integrates.
void and;
