/**
 * Admin API layer - connects to the FastAPI backend.
 */

import { api, setToken, clearToken } from './client';
import type {
  User, CreditRecord, Project, GenerationRecord, GenerationParams,
  Industry, AdminUser, AdminStats, ModelConfig, SystemConfig, AdminNotification,
  GenerationAiEnginesResponse, GenerationAITaskListOut, GenerationAITaskQueryParams,
  AdminHotOpeningTaskQueryParams, HotOpeningTaskListOut, ReplicationProjectDetailOut,
  AdminShotTaskSetQueryParams, ShotTaskSetListOut, ShotTaskSetDetailOut,
  AdminShotSegmentQueryParams, ShotSegmentListOut, ShotSegmentDetailOut,
  VideoPromptSchemaConfigOut, VideoPromptSchemaConfigSavePayload,
  VideoPromptSchemaPreviewPayload, VideoPromptSchemaPreviewOut, VideoPromptSchemaExportOut,
  AdminCreditRecordListResponse, AdminCreditRecordQueryParams,
} from '../types';

// ── Auth ──────────────────────────────────────────────────

export async function login(username: string, password: string, captchaToken?: string, rememberMe?: boolean): Promise<User> {
  const res = await api.post<{ accessToken: string; user: User }>('/auth/admin-login', { username, password, captcha_token: captchaToken, remember_me: rememberMe || false }, false);
  setToken(res.accessToken);
  return res.user;
}

export async function logout(): Promise<void> {
  await api.post('/auth/logout');
  clearToken();
}

export async function getUser(): Promise<User | null> {
  try {
    return await api.get<User>('/auth/me');
  } catch {
    return null;
  }
}

export async function changePassword(oldPwd: string, newPwd: string): Promise<void> {
  await api.post('/auth/change-password', { old_password: oldPwd, new_password: newPwd });
}

// ── Projects ──────────────────────────────────────────────

export async function getProjects(): Promise<Project[]> {
  return api.get<Project[]>('/projects');
}

export async function createProject(name: string, industry: Industry): Promise<Project> {
  return api.post<Project>('/projects', { name, industry });
}

export async function deleteProject(id: string): Promise<void> {
  await api.delete(`/projects/${id}`);
}

// ── Generation ────────────────────────────────────────────

export async function getRecords(projectId?: string): Promise<GenerationRecord[]> {
  const q = projectId ? `?project_id=${projectId}` : '';
  return api.get<GenerationRecord[]>(`/generation-records${q}`);
}

export async function optimizePrompt(projectId: string, params: GenerationParams): Promise<any> {
  return api.post('/generation-records/optimize', { project_id: projectId, ...params });
}

export async function generateVideo(recordId: string): Promise<GenerationRecord> {
  return api.post<GenerationRecord>(`/generation-records/${recordId}/generate`);
}

// ── Credits ───────────────────────────────────────────────

export async function getCredits(): Promise<{ credits: number; records: CreditRecord[] }> {
  return api.get('/credits');
}

// ── Notifications ─────────────────────────────────────────

export async function getNotifications(): Promise<AdminNotification[]> {
  return api.get('/notifications');
}

export async function getUnreadCount(): Promise<number> {
  const res = await api.get<{ count: number }>('/notifications/unread-count');
  return res.count;
}

export async function markNotificationRead(id: string): Promise<void> {
  await api.put(`/notifications/${id}/read`);
}

// ── Admin ─────────────────────────────────────────────────

export async function getAdminStats(startDate?: string, endDate?: string): Promise<AdminStats> {
  const params: Record<string, string> = {};
  if (startDate) params.start_date = startDate;
  if (endDate) params.end_date = endDate;
  const query = new URLSearchParams(params).toString();
  return api.get(`/admin/stats${query ? `?${query}` : ''}`);
}

export async function getAdminUsers(
  page = 1,
  pageSize = 20,
  search?: string,
  userType?: string,
  frontendUserKind?: string,
): Promise<{ items: AdminUser[]; total: number }> {
  const params = new URLSearchParams();
  params.set('page', String(page));
  params.set('page_size', String(pageSize));
  if (search) params.set('search', search);
  if (userType) params.set('user_type', userType);
  if (frontendUserKind) params.set('frontend_user_kind', frontendUserKind);
  return api.get(`/admin/users?${params.toString()}`);
}

export async function updateFrontendUserKind(userId: string, frontendUserKind: 'internal' | 'external'): Promise<AdminUser> {
  return api.put(`/admin/users/${userId}/frontend-kind`, { frontend_user_kind: frontendUserKind });
}

export async function adjustCredits(userId: string, amount: number, description: string): Promise<void> {
  await api.post(`/admin/users/${userId}/credits`, { amount, description });
}

export async function toggleUserStatus(userId: string, isActive: boolean): Promise<void> {
  await api.put(`/admin/users/${userId}/status`, { is_active: isActive });
}

export async function getModelConfigs(): Promise<ModelConfig[]> {
  return api.get('/admin/model-configs');
}

export async function saveModelConfig(config: Partial<ModelConfig> & { id?: string }): Promise<ModelConfig> {
  if (config.id) return api.put(`/admin/model-configs/${config.id}`, config);
  return api.post('/admin/model-configs', config);
}

export async function deleteModelConfig(id: string): Promise<void> {
  await api.delete(`/admin/model-configs/${id}`);
}

export async function getSystemConfigs(): Promise<SystemConfig[]> {
  return api.get('/admin/system-configs');
}

export async function updateSystemConfig(id: string, value: string): Promise<void> {
  await api.put(`/admin/system-configs/${id}`, { value });
}

export async function uploadPdf(file: File, configKey: string): Promise<{ url: string }> {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('config_key', configKey);
  const token = localStorage.getItem('auth_token');
  const baseUrl = import.meta.env.VITE_API_BASE || 'http://localhost:8000';
  const res = await fetch(`${baseUrl}/api/admin/upload-pdf`, {
    method: 'POST',
    headers: token ? { 'Authorization': `Bearer ${token}` } : {},
    body: formData,
  });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(text || '上传失败');
  }
  return res.json();
}

export async function uploadLogo(file: File): Promise<{ url: string }> {
  const formData = new FormData();
  formData.append('file', file);
  const token = localStorage.getItem('auth_token');
  const baseUrl = import.meta.env.VITE_API_BASE || 'http://localhost:8000';
  const res = await fetch(`${baseUrl}/api/admin/upload-logo`, {
    method: 'POST',
    headers: token ? { 'Authorization': `Bearer ${token}` } : {},
    body: formData,
  });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(text || '上传失败');
  }
  return res.json();
}

function setMaybe(params: URLSearchParams, key: string, value: unknown): void {
  if (value !== undefined && value !== null && String(value) !== '') params.set(key, String(value));
}

export async function getCreditRecords(filters?: AdminCreditRecordQueryParams): Promise<AdminCreditRecordListResponse> {
  const params = new URLSearchParams();
  setMaybe(params, 'page', filters?.page);
  setMaybe(params, 'page_size', filters?.pageSize);
  setMaybe(params, 'user_id', filters?.userId);
  setMaybe(params, 'user_name', filters?.userName);
  setMaybe(params, 'user_type', filters?.userType);
  setMaybe(params, 'frontend_user_kind', filters?.frontendUserKind);
  setMaybe(params, 'record_type', filters?.recordType || filters?.type);
  setMaybe(params, 'credit_subject', filters?.creditSubject);
  setMaybe(params, 'media_type', filters?.mediaType);
  setMaybe(params, 'charge_kind', filters?.chargeKind);
  setMaybe(params, 'source_module', filters?.sourceModule);
  setMaybe(params, 'source_step_code', filters?.sourceStepCode);
  setMaybe(params, 'billing_scene', filters?.billingScene);
  setMaybe(params, 'start_date', filters?.startDate);
  setMaybe(params, 'end_date', filters?.endDate);
  const q = params.toString() ? `?${params}` : '';
  return api.get(`/admin/credit-records${q}`);
}

export async function getIndustryConfigs(): Promise<any[]> {
  return api.get('/admin/industry-configs');
}

export async function saveIndustryConfig(config: any): Promise<any> {
  if (config.id) return api.put(`/admin/industry-configs/${config.id}`, config);
  return api.post('/admin/industry-configs', config);
}

export async function deleteIndustryConfig(id: string): Promise<void> {
  await api.delete(`/admin/industry-configs/${id}`);
}

export async function getVideoEngines(): Promise<any[]> {
  return api.get('/admin/video-engines');
}

export async function saveVideoEngine(engine: any): Promise<any> {
  if (engine.id) return api.put(`/admin/video-engines/${engine.id}`, engine);
  return api.post('/admin/video-engines', engine);
}

export async function deleteVideoEngine(id: string): Promise<void> {
  await api.delete(`/admin/video-engines/${id}`);
}

export async function getImageEngines(): Promise<any[]> {
  return api.get('/admin/image-engines');
}

export async function saveImageEngine(engine: any): Promise<any> {
  if (engine.id) return api.put(`/admin/image-engines/${engine.id}`, engine);
  return api.post('/admin/image-engines', engine);
}

export async function deleteImageEngine(id: string): Promise<void> {
  await api.delete(`/admin/image-engines/${id}`);
}

export async function getCreditRatios(): Promise<any[]> {
  return api.get('/admin/credit-ratios');
}

export async function saveCreditRatio(ratio: any): Promise<any> {
  if (ratio.id) return api.put(`/admin/credit-ratios/${ratio.id}`, ratio);
  return api.post('/admin/credit-ratios', ratio);
}

export async function deleteCreditRatio(id: string): Promise<void> {
  await api.delete(`/admin/credit-ratios/${id}`);
}

export async function getPaymentConfigs(): Promise<any[]> {
  return api.get('/admin/payment-configs');
}

export async function updatePaymentConfig(id: string, value: string): Promise<void> {
  await api.put(`/admin/payment-configs/${id}`, { value });
}

export async function batchUpdatePaymentConfigs(configs: Record<string, string>): Promise<void> {
  await api.put('/admin/payment-configs/batch', configs);
}

export async function getPaymentStats(params?: {
    paymentMethod?: string;
    status?: string;
    startDate?: string;
    endDate?: string;
}): Promise<{
    byStatus: Record<string, { count: number; amount: number }>;
    today: { paidCount: number; paidAmount: number };
    month: { paidCount: number; paidAmount: number };
    recent: any[];
}> {
    const searchParams = new URLSearchParams();
    if (params?.paymentMethod) searchParams.set('payment_method', params.paymentMethod);
    if (params?.status) searchParams.set('status', params.status);
    if (params?.startDate) searchParams.set('start_date', params.startDate);
    if (params?.endDate) searchParams.set('end_date', params.endDate);
    const queryString = searchParams.toString();
    const url = queryString ? `/admin/payment-stats?${queryString}` : '/admin/payment-stats';
    return api.get(url);
}

export async function getAdminPaymentOrders(params?: { method?: string; status?: string; startDate?: string; endDate?: string; page?: number; pageSize?: number }): Promise<{ items: any[]; total: number }> {
  const qs = new URLSearchParams();
  if (params?.method) qs.set('payment_method', params.method);
  if (params?.status) qs.set('status', params.status);
  if (params?.startDate) qs.set('start_date', params.startDate);
  if (params?.endDate) qs.set('end_date', params.endDate);
  if (params?.page) qs.set('page', String(params.page));
  if (params?.pageSize) qs.set('page_size', String(params.pageSize));
  return api.get(`/admin/payment-orders?${qs.toString()}`);
}

export async function refundPaymentOrder(orderNo: string): Promise<void> {
  await api.post(`/admin/payment-orders/${orderNo}/refund`);
}

export async function getAdminNotifications(page = 1, pageSize = 20): Promise<{ total: number; items: any[] }> {
  const params = new URLSearchParams();
  params.set('page', String(page));
  params.set('page_size', String(pageSize));
  return api.get(`/admin/notifications?${params.toString()}`);
}

export async function createAdminNotification(data: { title: string; content: string; type: string; target_user_id?: string }): Promise<void> {
  await api.post('/admin/notifications', data);
}

export async function deleteAdminNotification(id: string): Promise<void> {
  await api.delete(`/admin/notifications/${id}`);
}

export async function getNotificationReadUsers(id: string): Promise<{ total: number; items: { userId: string; username: string; readAt: string }[] }> {
  return api.get(`/admin/notifications/${id}/read-users`);
}

// ── Menu Config ─────────────────────────────────────────

export async function getMenuConfigs(): Promise<any[]> {
  return api.get('/admin/menu-configs');
}

export async function saveMenuConfig(config: any): Promise<any> {
  if (config.id) return api.put(`/admin/menu-configs/${config.id}`, config);
  return api.post('/admin/menu-configs', config);
}

export async function deleteMenuConfig(id: string): Promise<void> {
  await api.delete(`/admin/menu-configs/${id}`);
}

// ── User Creation ───────────────────────────────────────

export async function createUser(data: { username?: string; password: string; email?: string; phone?: string; credits: number; user_type: string; frontend_user_kind?: string; allowed_menus?: string[] | null }): Promise<any> {
  return api.post('/admin/users', data);
}

export async function updateUserMenus(userId: string, allowedMenus: string[] | null): Promise<void> {
  await api.put(`/admin/users/${userId}/menus`, { allowed_menus: allowedMenus });
}

export async function resetUserPassword(userId: string, newPassword: string): Promise<void> {
  await api.put(`/admin/users/${userId}/reset-password`, { new_password: newPassword });
}

export async function adminChangePassword(oldPwd: string, newPwd: string): Promise<void> {
  await api.post('/admin/change-password', { old_password: oldPwd, new_password: newPwd });
}

export async function getSiteInfo(): Promise<{ siteName: string; siteLogo: string; userAgreementUrl: string; privacyPolicyUrl: string }> {
  return api.get('/auth/site-info', false);
}

// ── Recharge Packages ───────────────────────────────────

export async function getRechargePackages(): Promise<any[]> {
  return api.get('/admin/recharge-packages');
}

export async function saveRechargePackage(pkg: any): Promise<any> {
  if (pkg.id) return api.put(`/admin/recharge-packages/${pkg.id}`, pkg);
  return api.post('/admin/recharge-packages', pkg);
}

export async function deleteRechargePackage(id: string): Promise<void> {
  await api.delete(`/admin/recharge-packages/${id}`);
}

// ── Operation Logs ──────────────────────────────────────

export async function getOperationLogs(page?: number): Promise<{ total: number; items: any[] }> {
  const q = page ? `?page=${page}` : '';
  return api.get(`/admin/operation-logs${q}`);
}

// ── oauthapp List ──────────────────────────────────────

export async function getOauthAppList(page?: number): Promise<{ total: number; items: any[] }> {
  const q = page ? `?page=${page}` : '';
  return api.get(`/admin/user-oauth-apps/list${q}`);
}

export async function createOauthApp(data: {
  app_id: string;
  secret: string;
  open_type: number;
  count?: number;
  auth_url?: string;
  company?: string;
}): Promise<any> {
  return api.post('/admin/user-oauth-apps/create', data);
}

export async function getOauthApp(id: string): Promise<any> {
  return api.get(`/admin/user-oauth-apps/read/${id}`);
}

export async function updateOauthApp(id: string, data: {
  app_id?: string;
  secret?: string;
  open_type?: number;
  count?: number;
  auth_url?: string;
  company?: string;
}): Promise<any> {
  return api.post(`/admin/user-oauth-apps/update/${id}`, data);
}

export async function deleteOauthApp(id: string): Promise<void> {
  await api.get(`/admin/user-oauth-apps/delete/${id}`);
}

// ── Open Type ───────────────────────────────────────────────

export async function getOpenTypeList(params?: {
  page?: number;
  page_size?: number;
  type_name?: string;
  open_type?: number;
}): Promise<{
  pagination: any;
  data: never[];
}> {
  const q = new URLSearchParams();
  if (params?.page) q.set('page', String(params.page));
  if (params?.page_size) q.set('page_size', String(params.page_size));
  if (params?.type_name) q.set('type_name', params.type_name);
  if (params?.open_type) q.set('open_type', String(params.open_type));
  const qs = q.toString();
  return api.get(`/open-type/list${qs ? `?${qs}` : ''}`);
}

export async function getOpenType(id: string): Promise<any> {
  return api.get(`/open-type/select/${id}`);
}

export async function createOpenType(data: {
  open_type: number;
  description: string;
  type_name: string;
  thumb?: string;
}): Promise<any> {
  return api.post('/open-type/create', data);
}

export async function updateOpenType(id: string, data: {
  open_type?: number;
  description?: string;
  type_name?: string;
  thumb?: string;
}): Promise<any> {
  return api.put(`/open-type/update/${id}`, data);
}

export async function deleteOpenType(id: string): Promise<void> {
  await api.delete(`/open-type/delete/${id}`);
}

export interface OpenTypeItem {
  id: string;
  openType: number;
  typeName: string;
  description: string;
  thumb?: string;
}

export async function getOpenTypeAll(): Promise<{ data: OpenTypeItem[] }> {
  return api.get('/open-type/open_type_all');
}

// ── Generation Records (Admin) ─────────────────────────────

export async function getAdminGenerationRecords(params?: {
  userId?: string; status?: string; page?: number; pageSize?: number;
}): Promise<{ total: number; items: any[] }> {
  const q = new URLSearchParams();
  if (params?.userId) q.set('user_id', params.userId);
  if (params?.status) q.set('status', params.status);
  if (params?.page) q.set('page', String(params.page));
  if (params?.pageSize) q.set('page_size', String(params.pageSize));
  const qs = q.toString();
  return api.get(`/admin/generation-records${qs ? `?${qs}` : ''}`);
}

export async function adminUpdateGenerationStatus(
  recordId: string, status: string, videoUrl?: string
): Promise<void> {
  await api.put(`/admin/generation-records/${recordId}/status`, { status, video_url: videoUrl });
}

export async function adminGenerateVideo(
  recordId: string, aspectRatio: string, resolution: string, image_size: string
): Promise<void> {
  await api.post(`/admin/generation-records/${recordId}/generate`, { aspect_ratio: aspectRatio, resolution, image_size });
}

// ── Generation AI Engines (Admin) ─────────────────────────────

export async function getGenerationAiEngines(): Promise<GenerationAiEnginesResponse> {
  return api.get<GenerationAiEnginesResponse>(`/generation-ai/engines`);
}

export async function getAdminGenerationAiTasks(params?: GenerationAITaskQueryParams): Promise<GenerationAITaskListOut> {
  const q = new URLSearchParams();
  if (params?.genType) q.set('gen_type', params.genType);
  if (params?.status) q.set('status', params.status);
  if (params?.page) q.set('page', String(params.page));
  if (params?.pageSize) q.set('page_size', String(params.pageSize));
  if (params?.userId) q.set('user_id', params.userId);
  if (params?.userName) q.set('user_name', params.userName);
  const qs = q.toString();
  return api.get<GenerationAITaskListOut>(`/generation-ai/tasks${qs ? `?${qs}` : ''}`);
}



// ── Replication Modules (Admin readonly pages reuse original APIs) ───────────

function appendParam(params: URLSearchParams, key: string, value?: string | number | null): void {
  if (value === undefined || value === null || String(value).trim() === '') return;
  params.set(key, String(value));
}

export async function getAdminHotOpeningTasks(params?: AdminHotOpeningTaskQueryParams): Promise<HotOpeningTaskListOut> {
  const q = new URLSearchParams();
  appendParam(q, 'status', params?.status);
  appendParam(q, 'keyword', params?.keyword);
  appendParam(q, 'user_id', params?.userId);
  appendParam(q, 'user_name', params?.userName);
  appendParam(q, 'created_start', params?.createdStart);
  appendParam(q, 'created_end', params?.createdEnd);
  appendParam(q, 'page', params?.page);
  appendParam(q, 'page_size', params?.pageSize);
  const qs = q.toString();
  return api.get<HotOpeningTaskListOut>(`/hot-opening-replications/tasks${qs ? `?${qs}` : ''}`);
}

export async function getAdminHotOpeningTaskDetail(projectId: string): Promise<ReplicationProjectDetailOut> {
  return api.get<ReplicationProjectDetailOut>(`/hot-opening-replications/tasks/${projectId}`);
}

export async function getAdminShotTaskSets(params?: AdminShotTaskSetQueryParams): Promise<ShotTaskSetListOut> {
  const q = new URLSearchParams();
  appendParam(q, 'status', params?.status);
  appendParam(q, 'analysis_status', params?.analysisStatus);
  appendParam(q, 'split_status', params?.splitStatus);
  appendParam(q, 'keyword', params?.keyword);
  appendParam(q, 'user_id', params?.userId);
  appendParam(q, 'user_name', params?.userName);
  appendParam(q, 'created_start', params?.createdStart);
  appendParam(q, 'created_end', params?.createdEnd);
  appendParam(q, 'page', params?.page);
  appendParam(q, 'page_size', params?.pageSize);
  const qs = q.toString();
  return api.get<ShotTaskSetListOut>(`/shot-replications/task-sets${qs ? `?${qs}` : ''}`);
}

export async function getAdminShotTaskSetDetail(taskSetId: string): Promise<ShotTaskSetDetailOut> {
  return api.get<ShotTaskSetDetailOut>(`/shot-replications/task-sets/${taskSetId}`);
}

export async function getAdminShotSegments(taskSetId: string, params?: AdminShotSegmentQueryParams): Promise<ShotSegmentListOut> {
  const q = new URLSearchParams();
  appendParam(q, 'source_mode', params?.sourceMode);
  appendParam(q, 'split_status', params?.splitStatus);
  appendParam(q, 'analysis_status', params?.analysisStatus);
  appendParam(q, 'replicate_status', params?.replicateStatus);
  appendParam(q, 'page', params?.page);
  appendParam(q, 'page_size', params?.pageSize);
  const qs = q.toString();
  return api.get<ShotSegmentListOut>(`/shot-replications/task-sets/${taskSetId}/segments${qs ? `?${qs}` : ''}`);
}

export async function getAdminShotSegmentDetail(segmentId: string): Promise<ShotSegmentDetailOut> {
  return api.get<ShotSegmentDetailOut>(`/shot-replications/segments/${segmentId}`);
}

export async function getAdminShotProjectDetail(projectId: string): Promise<ReplicationProjectDetailOut> {
  return api.get<ReplicationProjectDetailOut>(`/shot-replications/projects/${projectId}`);
}


// ── Video Prompt Schema Config (Admin) ─────────────────────

export async function getVideoPromptSchemaConfig(): Promise<VideoPromptSchemaConfigOut> {
  return api.get<VideoPromptSchemaConfigOut>('/admin/video-prompt-schema-config');
}

export async function saveVideoPromptSchemaConfig(payload: VideoPromptSchemaConfigSavePayload): Promise<VideoPromptSchemaConfigOut> {
  return api.put<VideoPromptSchemaConfigOut>('/admin/video-prompt-schema-config', payload);
}

export async function resetVideoPromptSchemaConfig(): Promise<VideoPromptSchemaConfigOut> {
  return api.post<VideoPromptSchemaConfigOut>('/admin/video-prompt-schema-config/reset-default');
}

export async function exportVideoPromptSchemaConfig(): Promise<VideoPromptSchemaExportOut> {
  return api.get<VideoPromptSchemaExportOut>('/admin/video-prompt-schema-config/export');
}

export async function importVideoPromptSchemaConfig(payload: VideoPromptSchemaConfigSavePayload): Promise<VideoPromptSchemaConfigOut> {
  return api.post<VideoPromptSchemaConfigOut>('/admin/video-prompt-schema-config/import', payload);
}

export async function previewVideoPromptSchemaConfig(payload: VideoPromptSchemaPreviewPayload): Promise<VideoPromptSchemaPreviewOut> {
  return api.post<VideoPromptSchemaPreviewOut>('/admin/video-prompt-schema-config/preview', payload);
}

// 获取授权链接
export interface RequestOAuthParams {
  open_type: number;
}
export async function requestOAuth(params: RequestOAuthParams): Promise<any> {
  return api.post(`/user-oauth/request_oauth`, params);
}

// 授权列表
export interface OAuthListParams {
  account_userid?: string;
  open_type?: number;
  account_id?: string;
  page?: number;
  page_size?: number;
}
export async function getOAuthList(params: OAuthListParams): Promise<any> {
  const query = new URLSearchParams();
  if (params.account_userid) query.set('account_userid', params.account_userid);
  if (params.open_type !== undefined) query.set('open_type', String(params.open_type));
  if (params.account_id) query.set('account_id', params.account_id);
  if (params.page !== undefined) query.set('page', String(params.page));
  if (params.page_size !== undefined) query.set('page_size', String(params.page_size));
  return api.get(`/user-oauth/oauth_list?${query.toString()}`);
}

export async function uploadImage(file: File): Promise<{ url: string; filename: string }> {
  const form = new FormData();
  form.append('file', file);
  const token = localStorage.getItem('auth_token');
  const res = await fetch(`${import.meta.env.VITE_API_BASE || 'http://localhost:8000'}/api/generation-records/upload-image`, {
    method: 'POST',
    headers: token ? { Authorization: `Bearer ${token}` } : {},
    body: form,
  });
  if (!res.ok) throw new Error('图片上传失败');
  const data = await res.json();
  return { url: data.url, filename: data.filename };
}

// 自定义表头字段
export async function getFields(): Promise<any> {
  return api.get('/material-consumption/fields');
}

// 查询素材消耗列表
export interface MaterialConsumpParams {
  advertiser_id?: string;
  user_id?: string;
  consume_date?: [string, string];
  page?: number;
  page_size?: number;
}
export async function getMaterialConsumpList(params: MaterialConsumpParams): Promise<any> {
  const query = new URLSearchParams();
  if (params.advertiser_id) query.set('advertiser_id', params.advertiser_id);
  if (params.user_id) query.set('user_id', params.user_id);
  if (params.consume_date !== undefined) query.set('consume_date', params.consume_date[0] + ',' + params.consume_date[1]);
  if (params.page !== undefined) query.set('page', String(params.page));
  if (params.page_size !== undefined) query.set('page_size', String(params.page_size));
  return api.get(`/material-consumption/admin/list?${query.toString()}`);
}