import apiClient from '@/infrastructure/api/client';
import { API_ENDPOINTS } from '@/infrastructure/api/endpoints';

export type AppAssetType = 'SPLASH' | 'GUIDE';

export interface AppAsset {
  id: string;
  type: AppAssetType;
  sortOrder: number;
  imageUrl: string;
  title: string | null;
  subtitle: string | null;
  isEnabled: boolean;
  createdAt: string;
  updatedAt: string;
}

export const appAssetService = {
  /** 查询资源列表 */
  async list(type?: AppAssetType): Promise<AppAsset[]> {
    const params = type ? { type } : {};
    return apiClient.get(API_ENDPOINTS.APP_ASSETS.LIST, { params });
  },

  /** 上传图片并创建/替换资源 */
  async upload(
    file: File,
    type: AppAssetType,
    sortOrder: number,
    title?: string,
    subtitle?: string,
  ): Promise<AppAsset> {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('type', type);
    formData.append('sortOrder', String(sortOrder));
    if (title) formData.append('title', title);
    if (subtitle) formData.append('subtitle', subtitle);

    return apiClient.post(API_ENDPOINTS.APP_ASSETS.UPLOAD, formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });
  },

  /** 更新资源元数据 */
  async update(
    id: string,
    data: { title?: string; subtitle?: string; isEnabled?: boolean },
  ): Promise<AppAsset> {
    return apiClient.put(API_ENDPOINTS.APP_ASSETS.UPDATE(id), data);
  },

  /** 删除资源 */
  async delete(id: string): Promise<void> {
    return apiClient.delete(API_ENDPOINTS.APP_ASSETS.DELETE(id));
  },
};

export default appAssetService;
