// Types
export interface BotToken {
  characterId: string;
  characterName?: string;
  botUsername?: string;
  isActive: boolean;
  token?: string;
}

export interface WebhookStatus {
  characterId: string;
  botUsername?: string;
  webhookUrl?: string;
  isConfigured: boolean;
}

export interface ChannelInfo {
  normal?: { chatId?: string; title?: string; inviteLink?: string; memberCount?: number };
  vip?: { chatId?: string; title?: string; inviteLink?: string; memberCount?: number; starPrice?: number };
}

export interface Conversation {
  telegramUserId: number;
  userName?: string;
  totalMessages: number;
  starsSpent?: number;
  lastActivity: string;
  lastMessagePreview?: string | null;
}

export interface Message {
  id: string;
  role: 'user' | 'assistant';
  content: string;
  timestamp: string;
  messageType?: 'text' | 'photo' | 'text_photo';
  imagePath?: string;
  imageUrl?: string;
  metadata?: { photoSent?: boolean };
}

export interface StarsStats {
  totalEarned: number;
  totalTransactions: number;
  byType?: { payment: number; reaction: number };
}

export interface StarsTransaction {
  id: string;
  type: string;
  starCount: number;
  status: string;
  createdAt: string;
}

export interface CharacterSummary {
  id: string;
  identity: { name: string };
  status: 'active' | 'inactive' | 'creating';
}

// Helper functions
export function maskToken(token: string): string {
  if (!token) return '';
  if (token.length <= 4) return token;
  return '*'.repeat(token.length - 4) + token.slice(-4);
}

export function formatWebhookUrl(baseUrl: string, token: string): string {
  const cleanBase = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
  return `${cleanBase}/api/v1/webhooks/telegram/${token}`;
}

export function sortConversationsByDate(conversations: Conversation[]): Conversation[] {
  return [...conversations].sort((a, b) =>
    new Date(b.lastActivity).getTime() - new Date(a.lastActivity).getTime()
  );
}

export function sortMessagesByDate(messages: Message[]): Message[] {
  return [...messages].sort((a, b) =>
    new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
  );
}

export function filterTransactions(
  transactions: StarsTransaction[],
  typeFilter: string,
  statusFilter: string,
): StarsTransaction[] {
  return transactions.filter((tx) => {
    if (typeFilter && typeFilter !== 'all' && tx.type !== typeFilter) return false;
    if (statusFilter && statusFilter !== 'all' && tx.status !== statusFilter) return false;
    return true;
  });
}

export function formatDateTR(dateStr: string): string {
  if (!dateStr) return '—';
  try {
    return new Date(dateStr).toLocaleString('tr-TR');
  } catch {
    return '—';
  }
}