// 文件管理 API — 对接 Gateway REST API

import { request } from './client';

/** 文件元信息 */
export interface FileInfo {
  id: string;
  user_id: string;
  filename: string;
  mime_type: string;
  size: number;
  hash: string;
  is_public: boolean;
  created_at: string; // UnixMilli
  url: string;
  thumbnail_url?: string;
}

/** 文件列表响应 */
interface FileListResponse {
  files: FileInfo[];
  total: number;
  page: number;
  limit: number;
}

/** 单文件响应 */
interface FileResponse {
  id: string;
  user_id: string;
  filename: string;
  mime_type: string;
  size: number;
  hash: string;
  is_public: boolean;
  created_at: number;
  url: string;
  thumbnail_url?: string;
}

const API_BASE = import.meta.env.VITE_API_URL || '/api/v1';

/**
 * 获取带授权头的文件下载/缩略图 URL (用于 fetch 直接获取 blob)
 */
function authFetch(url: string, init?: RequestInit): Promise<Response> {
  const token = localStorage.getItem('token');
  return fetch(url, {
    ...init,
    headers: {
      ...(init?.headers || {}),
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    },
  });
}

/**
 * 上传文件
 * POST /api/v1/files/upload (multipart/form-data)
 */
export async function uploadFile(
  file: File,
  sessionId?: string,
): Promise<FileInfo> {
  const token = localStorage.getItem('token');
  const formData = new FormData();
  formData.append('file', file);
  if (sessionId) {
    formData.append('session_id', sessionId);
  }

  const resp = await fetch(`${API_BASE}/files/upload`, {
    method: 'POST',
    headers: {
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    },
    body: formData,
  });

  if (!resp.ok) {
    const err = await resp.json().catch(() => ({ error: '上传失败' }));
    throw new Error(err.error || `上传失败 (${resp.status})`);
  }

  return resp.json();
}

/**
 * 列出用户的所有文件 (支持分页)
 * GET /api/v1/files?page=&limit=
 */
export async function listFiles(
  page: number = 1,
  limit: number = 20,
): Promise<{ files: FileInfo[]; total: number }> {
  const resp = await request<FileListResponse>(
    `/files?page=${page}&limit=${limit}`,
  );
  if (resp.error) {
    console.error('[files] 获取文件列表失败:', resp.error);
    return { files: [], total: 0 };
  }
  const data = resp.data as FileListResponse;
  return { files: data?.files || [], total: data?.total || 0 };
}

/**
 * 获取单个文件元数据
 * GET /api/v1/files/:id
 */
export async function getFile(id: string): Promise<FileInfo | null> {
  const resp = await request<FileResponse>(`/files/${encodeURIComponent(id)}`);
  if (resp.error) {
    console.error('[files] 获取文件信息失败:', resp.error);
    return null;
  }
  const data = resp.data;
  if (!data) return null;
  return {
    ...data,
    created_at: String(data.created_at),
    thumbnail_url: data.thumbnail_url,
  };
}

/**
 * 删除文件
 * DELETE /api/v1/files/:id
 */
export async function deleteFile(id: string): Promise<boolean> {
  const resp = await request(`/files/${encodeURIComponent(id)}`, {
    method: 'DELETE',
  });
  if (resp.error) {
    console.error('[files] 删除文件失败:', resp.error);
    return false;
  }
  return true;
}

/**
 * 获取文件下载URL
 */
export function getFileDownloadUrl(id: string): string {
  return `${API_BASE}/files/${encodeURIComponent(id)}/download`;
}

/**
 * 获取文件缩略图URL
 */
export function getFileThumbnailUrl(id: string): string {
  return `${API_BASE}/files/${encodeURIComponent(id)}/thumbnail`;
}

/**
 * 通过 fetch 下载文件并触发浏览器下载
 */
export async function downloadFile(id: string, filename?: string): Promise<void> {
  const resp = await authFetch(getFileDownloadUrl(id));
  if (!resp.ok) {
    const err = await resp.json().catch(() => ({ error: '下载失败' }));
    throw new Error(err.error || `下载失败 (${resp.status})`);
  }

  // 从 Content-Disposition 获取文件名
  const disposition = resp.headers.get('Content-Disposition');
  let downloadName = filename || 'download';
  if (disposition) {
    const match = disposition.match(/filename="?([^";\n]+)"?/);
    if (match) downloadName = match[1];
  }

  const blob = await resp.blob();
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = downloadName;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

/**
 * 获取缩略图 blob URL (用于 <img> 标签)
 */
export async function getThumbnailBlobUrl(id: string): Promise<string | null> {
  try {
    const resp = await authFetch(getFileThumbnailUrl(id));
    if (!resp.ok) return null;
    const blob = await resp.blob();
    return URL.createObjectURL(blob);
  } catch {
    return null;
  }
}
