import type { FileRecord } from '../types';

export function fileDisplayName(file: Pick<FileRecord, 'displayName' | 'originalName'>): string {
  const custom = file.displayName?.trim();
  return custom || file.originalName;
}

export function sortFilesByCreatedAsc(files: FileRecord[]): FileRecord[] {
  return [...files].sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
}

export function sortFilesByOrder(files: FileRecord[]): FileRecord[] {
  return [...files].sort((a, b) => {
    const orderDiff = (a.sortOrder ?? 0) - (b.sortOrder ?? 0);
    if (orderDiff !== 0) return orderDiff;
    return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
  });
}

export function isVideoFile(file: Pick<FileRecord, 'mimetype' | 'originalName'>): boolean {
  const name = file.originalName.toLowerCase();
  return (
    file.mimetype.startsWith('video/') ||
    /\.(mp4|mov|avi|webm|mkv|m4v|wmv)$/i.test(name)
  );
}

export function isExcelFile(file: Pick<FileRecord, 'mimetype' | 'originalName'>): boolean {
  const name = file.originalName.toLowerCase();
  return (
    file.mimetype.includes('spreadsheet') ||
    file.mimetype.includes('excel') ||
    name.endsWith('.xlsx') ||
    name.endsWith('.xls') ||
    name.endsWith('.csv')
  );
}

export type FilePreviewKind =
  | 'image'
  | 'video'
  | 'excel'
  | 'pdf'
  | 'docx'
  | 'pptx'
  | 'hwp'
  | 'text'
  | 'unsupported';

function extOf(name: string): string {
  return name.split('.').pop()?.toLowerCase() ?? '';
}

/** 미리보기 라우팅 — iframe 대신 형식별 뷰어 사용 */
export function getFilePreviewKind(
  file: Pick<FileRecord, 'mimetype' | 'originalName'>,
): FilePreviewKind {
  const name = file.originalName.toLowerCase();
  const ext = extOf(name);

  if (isExcelFile(file)) return 'excel';
  if (file.mimetype.startsWith('image/') || /^(png|jpe?g|gif|webp|bmp|svg)$/.test(ext)) return 'image';
  if (isVideoFile(file)) return 'video';
  if (file.mimetype === 'application/pdf' || ext === 'pdf') return 'pdf';
  if (file.mimetype.includes('wordprocessingml') || ext === 'docx') return 'docx';
  if (file.mimetype.includes('presentationml') || ext === 'pptx') return 'pptx';
  if (ext === 'hwp' || ext === 'hwpx' || file.mimetype.includes('hwp')) return 'hwp';
  if (file.mimetype.startsWith('text/') || ext === 'txt') return 'text';
  return 'unsupported';
}

const EXT_MIME: Record<string, string> = {
  pdf: 'application/pdf',
  png: 'image/png',
  jpg: 'image/jpeg',
  jpeg: 'image/jpeg',
  gif: 'image/gif',
  webp: 'image/webp',
  bmp: 'image/bmp',
  svg: 'image/svg+xml',
  mp4: 'video/mp4',
  mov: 'video/quicktime',
  avi: 'video/x-msvideo',
  webm: 'video/webm',
  mkv: 'video/x-matroska',
  m4v: 'video/x-m4v',
  wmv: 'video/x-ms-wmv',
  xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  xls: 'application/vnd.ms-excel',
  csv: 'text/csv',
  docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  doc: 'application/msword',
  pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  ppt: 'application/vnd.ms-powerpoint',
  hwp: 'application/x-hwp',
  hwpx: 'application/hwp+zip',
  txt: 'text/plain',
};

export function resolvePreviewMime(file: Pick<FileRecord, 'mimetype' | 'originalName'>): string {
  const ext = extOf(file.originalName);
  const fromExt = EXT_MIME[ext];
  const stored = file.mimetype?.trim() ?? '';
  if (!stored || stored === 'application/octet-stream') {
    return fromExt ?? stored ?? 'application/octet-stream';
  }
  if (fromExt && stored.includes('octet')) return fromExt;
  return stored;
}
