import type { Channel } from './channels.js';
import type { MessageStatus, AttemptRecord, Attachment } from './messages.js';

/** Safe attachment summary for daily logs / console — never stores file bytes. */
export interface AttachmentMeta {
  filename: string;
  contentType: string;
  size_bytes: number;
  url?: string;
}

/** Derive log-safe attachment metadata from request payloads (drops base64 content). */
export function toAttachmentMeta(attachments?: Attachment[]): AttachmentMeta[] | undefined {
  if (!attachments || attachments.length === 0) return undefined;
  return attachments.map((a) => {
    const b64 = String(a.content || '').replace(/\s+/g, '').replace(/=+$/, '');
    const size_bytes = b64 ? Math.max(0, Math.floor((b64.length * 3) / 4)) : 0;
    return {
      filename: a.filename || 'attachment',
      contentType: a.contentType || 'application/octet-stream',
      size_bytes,
      ...(a.url ? { url: a.url } : {}),
    };
  });
}

export interface LogMessageRecord {
  type?: 'message';
  message_id: string;
  request_id: string;
  ts: number;
  application: string;
  channel: Channel;
  provider: string | null;
  /** Display name at send time (kept in logs after the provider is deleted). */
  provider_name?: string;
  status: MessageStatus;
  latency_ms: number;
  attempts: AttemptRecord[];
  provider_response: Record<string, unknown> | null;
  error: { code: string; message: string } | null;
  recipient_masked: string;
  failover: boolean;
  subject?: string;
  body_preview?: string;
  body_stored?: string;
  /** Attachment filenames/types/sizes only — file bytes are never persisted in logs. */
  attachments?: AttachmentMeta[];
}

export interface LogDeliveryRecord {
  ev: 'delivery';
  msgId: string;
  status: MessageStatus;
  ts: number;
  provider?: string;
  details?: Record<string, unknown>;
}

export interface LogAuditRecord {
  type: 'audit';
  ts: number;
  event: string;
  details: string | Record<string, unknown>;
  actor?: string;
}

export type LogRecord = LogMessageRecord | LogDeliveryRecord | LogAuditRecord;

