import { Message } from '../types'
import { api } from '../services/api'
import { logger } from './logger'

// 下载文件
export function downloadFile(url: string, filename: string) {
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.target = '_blank';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

// 获取文件图标
export function getFileIcon(filename: string): string {
  const ext = filename.split('.').pop()?.toLowerCase();
  const iconMap: { [key: string]: string } = {
    'pdf': '📄',
    'doc': '📝', 'docx': '📝',
    'xls': '📊', 'xlsx': '📊',
    'txt': '📃',
    'zip': '📦', 'rar': '📦',
    'ppt': '📽️', 'pptx': '📽️'
  };
  return iconMap[ext || ''] || '📎';
}

// 格式化文件大小
export function formatFileSize(bytes?: number): string {
  if (!bytes) return '';
  if (bytes < 1024) return bytes + ' B';
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
  return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
}

// 刷新过期的媒体 URL
export async function refreshMediaUrl(
  msg: Message,
  activeContactId: number | null,
  token: string,
  setMessages: React.Dispatch<React.SetStateAction<Record<number, Message[]>>>
) {
  if (!activeContactId) return;
  try {
    const messages = await api.getMessages(token, activeContactId);
    const updatedMsg = messages.find(m => m.id === msg.id);
    if (updatedMsg && (updatedMsg.content_type === 'IMAGE' || updatedMsg.content_type === 'VIDEO')) {
      setMessages(prev => ({
        ...prev,
        [activeContactId]: (prev[activeContactId] || []).map(m =>
          m.id === msg.id ? { ...m, content: updatedMsg.content } : m
        )
      }));
    }
  } catch (error) {
    logger.error('Failed to refresh media URL', error);
  }
}
