import { apiRequest, buildUrl, type PaginatedResponse } from './base';
import type { File, DocumentType } from '~/models/file';

/**
 * 文件API服务
 */

interface FileFilterParams {
  documentTypeId?: string;
  status?: string;
  reviewStatus?: string;
  keyword?: string;
  startDate?: string;
  endDate?: string;
  page?: number;
  pageSize?: number;
}

// 获取文件列表
export async function getFiles(params?: FileFilterParams): Promise<PaginatedResponse<File>> {
  const url = buildUrl('/api/files', params);
  return apiRequest<PaginatedResponse<File>>(url);
}

// 获取单个文件
export async function getFile(id: string): Promise<File> {
  const url = buildUrl(`/api/files/${id}`);
  return apiRequest<File>(url);
}

// 上传文件
export async function uploadFile(formData: FormData): Promise<File> {
  const url = buildUrl('/api/files/upload');
  
  const response = await fetch(url, {
    method: 'POST',
    body: formData,
  });
  
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message || '文件上传失败');
  }
  
  return response.json().then(data => data.data);
}

// 删除文件
export async function deleteFile(id: string): Promise<void> {
  const url = buildUrl(`/api/files/${id}`);
  return apiRequest<void>(url, 'DELETE');
}

// 获取文档类型列表
export async function getDocumentTypes(): Promise<DocumentType[]> {
  const url = buildUrl('/api/document-types');
  return apiRequest<DocumentType[]>(url);
}

// 获取单个文档类型
export async function getDocumentType(id: string): Promise<DocumentType> {
  const url = buildUrl(`/api/document-types/${id}`);
  return apiRequest<DocumentType>(url);
}

// 创建文档类型
export async function createDocumentType(documentType: Omit<DocumentType, 'id' | 'createdAt' | 'updatedAt'>): Promise<DocumentType> {
  const url = buildUrl('/api/document-types');
  return apiRequest<DocumentType>(url, 'POST', documentType);
}

// 更新文档类型
export async function updateDocumentType(id: string, documentType: Partial<Omit<DocumentType, 'id' | 'createdAt' | 'updatedAt'>>): Promise<DocumentType> {
  const url = buildUrl(`/api/document-types/${id}`);
  return apiRequest<DocumentType>(url, 'PUT', documentType);
}

// 删除文档类型
export async function deleteDocumentType(id: string): Promise<void> {
  const url = buildUrl(`/api/document-types/${id}`);
  return apiRequest<void>(url, 'DELETE');
} 