import { fileRequestClient } from '#/api/request';

// --- 枚举 ---

export enum ResourceType {
  File = 'file',
  Folder = 'folder',
}

// --- 类型定义（file_system Go 响应为 PascalCase） ---

export namespace FileApi {
  // S3 原始文件信息
  export interface FileInfo {
    Key: string;
    Size: number;
    LastModified: string;
    ETag: string;
  }

  export interface ListFilesResult {
    Files: FileInfo[];
    NextContinuationToken: string | null;
  }

  export interface ListFilesParams {
    bucket_name: string;
    prefix?: string;
    max_keys?: number;
    token?: string;
  }

  // 数据库文件元数据
  export interface FileMeta {
    ID: string;
    FolderID: string;
    Name: string;
    S3Key: string;
    S3Bucket: string;
    Size: number;
    ContentType: string;
    OwnerID: string;
    CreatedAt: string;
    UpdatedAt: string;
  }

  // 分片上传
  export interface MultipartInitResult {
    upload_id: string;
  }

  export interface UploadPartResult {
    etag: string;
  }
}

export namespace FolderApi {
  export interface Folder {
    ID: string;
    ParentID: string | null;
    Name: string;
    OwnerID: string;
    CreatedAt: string;
    UpdatedAt: string;
  }

  export interface FolderWithChildren {
    Folder: Folder;
    SubFolders: Folder[];
    Files: FileApi.FileMeta[];
  }

  export interface CreateFolderParams {
    name: string;
    parent_id?: string | null;
  }

  export interface RenameFolderParams {
    name: string;
  }
}

export namespace ShareApi {
  export interface ShareLink {
    ID: string;
    ResourceType: string;
    ResourceID: string;
    Token: string;
    Password: string | null;
    ExpiresAt: string | null;
    DownloadCount: number;
    MaxDownloads: number | null;
    CreatedBy: string;
    CreatedAt: string;
  }

  export interface ShareInfo {
    Token: string;
    ResourceType: string;
    FileName: string;
    FileSize: number;
    HasPassword: boolean;
    ExpiresAt: string | null;
  }

  export interface CreateShareParams {
    resource_type: string;
    resource_id: string;
    password?: string;
    expires_at?: string;
    max_downloads?: number;
  }
}

// --- 文件操作（S3 原始） ---

export async function listFilesApi(params: FileApi.ListFilesParams) {
  return fileRequestClient.get<FileApi.ListFilesResult>('/files/list', {
    params,
  });
}

export async function uploadFileApi(bucketName: string, file: File) {
  const formData = new FormData();
  formData.append('bucket_name', bucketName);
  formData.append('file', file);
  return fileRequestClient.post<{ message: string }>('/files/upload', formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
  });
}

export async function deleteFileApi(bucketName: string, objectKey: string) {
  return fileRequestClient.delete<{ message: string }>('/files/delete', {
    data: { bucket_name: bucketName, object_key: objectKey },
  });
}

export async function downloadFileApi(bucketName: string, objectKey: string) {
  return fileRequestClient.get('/files/download', {
    params: { bucket_name: bucketName, object_key: objectKey },
    responseType: 'blob',
  });
}

export async function getFilePreviewApi(bucketName: string, objectKey: string) {
  return fileRequestClient.get<{ url: string }>('/files/preview', {
    params: { bucket_name: bucketName, object_key: objectKey },
  });
}

export async function getFileContentApi(bucketName: string, objectKey: string) {
  return fileRequestClient.get<{ content: string }>('/files/content', {
    params: { bucket_name: bucketName, object_key: objectKey },
  });
}

// --- 分片上传 ---

export async function initMultipartUploadApi(
  bucketName: string,
  objectKey: string,
) {
  return fileRequestClient.post<FileApi.MultipartInitResult>(
    '/files/multipart/init',
    { bucket_name: bucketName, object_key: objectKey },
  );
}

export async function uploadPartApi(
  bucketName: string,
  objectKey: string,
  uploadId: string,
  partNumber: number,
  data: Blob,
) {
  const formData = new FormData();
  formData.append('bucket_name', bucketName);
  formData.append('object_key', objectKey);
  formData.append('upload_id', uploadId);
  formData.append('part_number', String(partNumber));
  formData.append('data', data);
  return fileRequestClient.put<FileApi.UploadPartResult>(
    '/files/multipart/part',
    formData,
    { headers: { 'Content-Type': 'multipart/form-data' } },
  );
}

export async function completeMultipartUploadApi(
  bucketName: string,
  objectKey: string,
  uploadId: string,
  parts: { part_number: number; etag: string }[],
) {
  return fileRequestClient.post<{ message: string }>(
    '/files/multipart/complete',
    { bucket_name: bucketName, object_key: objectKey, upload_id: uploadId, parts },
  );
}

export async function abortMultipartUploadApi(
  bucketName: string,
  objectKey: string,
  uploadId: string,
) {
  return fileRequestClient.post<{ message: string }>(
    '/files/multipart/abort',
    { bucket_name: bucketName, object_key: objectKey, upload_id: uploadId },
  );
}

// --- 存储桶操作 ---

export async function listBucketsApi() {
  return fileRequestClient.get<{ buckets: string[] }>('/buckets');
}

export async function createBucketApi(bucketName: string) {
  return fileRequestClient.post<{ message: string }>('/buckets', {
    bucket_name: bucketName,
  });
}

export async function deleteBucketApi(bucketName: string) {
  return fileRequestClient.delete<{ message: string }>('/buckets', {
    data: { bucket_name: bucketName },
  });
}

// --- 文件夹操作 ---

export async function getFolderTreeApi() {
  return fileRequestClient.get<FolderApi.Folder[]>('/folders/tree');
}

export async function getFolderApi(folderId: string) {
  return fileRequestClient.get<FolderApi.FolderWithChildren>(
    `/folders/${folderId}`,
  );
}

export async function createFolderApi(params: FolderApi.CreateFolderParams) {
  return fileRequestClient.post<FolderApi.Folder>('/folders', params);
}

export async function renameFolderApi(
  folderId: string,
  params: FolderApi.RenameFolderParams,
) {
  return fileRequestClient.put<FolderApi.Folder>(
    `/folders/${folderId}`,
    params,
  );
}

export async function deleteFolderApi(folderId: string) {
  return fileRequestClient.delete<{ message: string }>(`/folders/${folderId}`);
}

export async function uploadToFolderApi(
  folderId: string,
  bucket: string,
  file: File,
) {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('bucket', bucket);
  return fileRequestClient.post<FileApi.FileMeta>(
    `/folders/${folderId}/files`,
    formData,
    { headers: { 'Content-Type': 'multipart/form-data' } },
  );
}

export async function moveFileApi(fileId: string, targetFolderId: string) {
  return fileRequestClient.post<{ message: string }>(`/files/${fileId}/move`, {
    target_folder_id: targetFolderId,
  });
}

// --- 分享操作 ---

export async function createShareApi(params: ShareApi.CreateShareParams) {
  return fileRequestClient.post<ShareApi.ShareLink>('/share', params);
}

export async function deleteShareApi(shareId: string) {
  return fileRequestClient.delete<{ message: string }>(`/share/${shareId}`);
}

export async function getShareInfoApi(token: string) {
  return fileRequestClient.get<ShareApi.ShareInfo>(`/share/${token}`);
}
