/**
 * 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,
} 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): 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);
  return api.get(`/admin/users?${params.toString()}`);
}

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 as any).env?.VITE_API_URL || 'http://localhost:8000/api';
  const res = await fetch(`${baseUrl}/admin/upload-pdf`, {
    method: 'POST',
    headers: token ? { 'Authorization': `Bearer ${token}` } : {},
    body: formData,
  });
  if (!res.ok) throw new Error('上传失败');
  return res.json();
}

export async function getCreditRecords(filters?: { 
  user_id?: string; 
  user_name?: string;
  type?: string;
  start_date?: string;
  end_date?: string;
}): Promise<any> {
  const params = new URLSearchParams();
  if (filters?.user_id) params.set('user_id', filters.user_id);
  if (filters?.user_name) params.set('user_name', filters.user_name);
  if (filters?.type) params.set('type', filters.type);
  if (filters?.start_date) params.set('start_date', filters.start_date);
  if (filters?.end_date) params.set('end_date', filters.end_date);
  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; 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}`);
}

// ── 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}` : ''}`);
}

