import { http } from './index';
import type { CourseCollectionResponse } from './generated/model';

export type { CourseCollectionResponse };

// ==================== 类型定义 ====================

export interface TenantQueryParams {
  pageNum?: number;
  pageSize?: number;
  keyword?: string;
  status?: string;
  collectionId?: number;
}

export interface Tenant {
  id: number;
  name: string;
  code: string;
  username?: string;
  contactName?: string;
  loginAccount?: string;
  address?: string;
  contactPerson?: string;
  contactPhone?: string;
  logoUrl?: string;
  packageNames?: string[];
  teacherQuota: number;
  studentQuota: number;
  storageQuota?: number;
  teacherCount?: number;
  studentCount?: number;
  storageUsed?: number;
  startDate?: string;
  expireDate?: string;
  status: string;
  createdAt: string;
  updatedAt?: string;
}

export interface TenantDetail extends Tenant {
  classCount?: number;
  lessonCount?: number;
  _count?: {
    teachers: number;
    students: number;
    classes: number;
    lessons: number;
  };
}

export interface CreateTenantDto {
  name: string;
  loginAccount: string;
  password?: string;
  address?: string;
  contactPerson?: string;
  contactPhone?: string;
  collectionIds?: number[];
  teacherQuota?: number;
  studentQuota?: number;
  startDate?: string;
  expireDate?: string;
}

export interface UpdateTenantDto {
  name?: string;
  address?: string;
  contactPerson?: string;
  contactPhone?: string;
  collectionIds?: number[];
  teacherQuota?: number;
  studentQuota?: number;
  startDate?: string;
  expireDate?: string;
  status?: string;
  forceRemove?: boolean;
}

export interface UpdateTenantQuotaDto {
  packageType?: string;
  teacherQuota?: number;
  studentQuota?: number;
}

// 后端返回的统计数据结构
export interface AdminStatsResponse {
  totalTenants: number;
  activeTenants: number;
  totalCourses: number;
  totalStudents: number;
  totalTeachers: number;
  totalLessons: number;
  monthlyLessons: number;
}

// 前端使用的统计数据结构
export interface AdminStats {
  tenantCount: number;
  activeTenantCount: number;
  courseCount: number;
  publishedCourseCount: number;
  studentCount: number;
  teacherCount: number;
  lessonCount: number;
  monthlyLessons: number;
}

// 后端返回的趋势数据结构（分离数组格式）
export interface StatsTrendResponse {
  dates: string[];
  lessonCounts: number[];
  studentCounts: number[];
}

// 前端使用的趋势数据结构
export interface TrendData {
  month: string;
  tenantCount: number;
  lessonCount: number;
  studentCount: number;
}

// 后端返回的活跃租户结构
export interface ActiveTenantResponse {
  tenantId: number;
  tenantName: string;
  activeTeacherCount: number;
  completedLessonCount: number;
}

// 前端使用的活跃租户结构
export interface ActiveTenant {
  id: number;
  name: string;
  activeTeacherCount: number;
  completedLessonCount: number;
}

// 后端返回的热门课程结构
export interface PopularCourseResponse {
  courseId: number;
  courseName: string;
  usageCount: number;
  teacherCount: number;
}

// 前端使用的热门课程结构
export interface PopularCourse {
  id: number;
  name: string;
  usageCount: number;
  teacherCount: number;
}

export interface CoursePackage {
  id: number;
  name: string;
  description: string;
  price: number;
  discountPrice?: number;
  discountType?: string;
  gradeLevels?: string[];
  courseCount: number;
  status: string;
  publishedAt?: string;
  createdAt?: string;
  updatedAt?: string;
}

export interface AdminSettings {
  // Basic settings
  systemName?: string;
  systemDesc?: string;
  contactPhone?: string;
  contactEmail?: string;
  systemLogo?: string;

  // Security settings
  passwordStrength?: string;
  maxLoginAttempts?: number;
  tokenExpire?: string;
  forceHttps?: boolean;

  // Notification settings
  emailEnabled?: boolean;
  smtpHost?: string;
  smtpPort?: number;
  smtpUser?: string;
  smtpPassword?: string;
  fromEmail?: string;
  smsEnabled?: boolean;

  // Storage settings
  storageType?: string;
  maxFileSize?: number;
  allowedTypes?: string;

  // Tenant defaults
  defaultTeacherQuota?: number;
  defaultStudentQuota?: number;
  enableAutoExpire?: boolean;
  notifyBeforeDays?: number;
}

// ==================== 租户管理 ====================

export const getTenants = (params: TenantQueryParams) =>
  http.get<{ list: Tenant[]; total: number; pageNum: number; pageSize: number; pages: number }>(
    '/v1/admin/tenants',
    { params }
  );

export const getTenant = (id: number) =>
  http.get<TenantDetail>(`/v1/admin/tenants/${id}`);

export const createTenant = (data: CreateTenantDto) => {
  // 映射前端字段到后端 API：loginAccount -> code, contactPerson -> contactName
  const payload = {
    ...data,
    code: data.loginAccount,
    contactName: data.contactPerson,
  };
  delete (payload as Record<string, unknown>).loginAccount;
  delete (payload as Record<string, unknown>).contactPerson;
  return http.post<Tenant & { tempPassword: string }>('/v1/admin/tenants', payload);
};

export const updateTenant = (id: number, data: UpdateTenantDto) => {
  // 映射前端字段到后端 API：contactPerson -> contactName
  const payload = { ...data, contactName: data.contactPerson };
  delete (payload as Record<string, unknown>).contactPerson;
  return http.put<Tenant>(`/v1/admin/tenants/${id}`, payload);
};

export const updateTenantQuota = (id: number, data: UpdateTenantQuotaDto) =>
  http.put<Tenant>(`/v1/admin/tenants/${id}/quota`, data);

export const updateTenantStatus = (id: number, status: string) =>
  http.put<{ id: number; name: string; status: string }>(`/v1/admin/tenants/${id}/status`, { status });

export const resetTenantPassword = (id: number) =>
  http.post<{ tempPassword: string }>(`/v1/admin/tenants/${id}/reset-password`);

export const deleteTenant = (id: number) =>
  http.delete<{ success: boolean }>(`/v1/admin/tenants/${id}`);

// ==================== 统计数据 ====================

// 数据映射函数：后端 -> 前端
const mapStatsData = (data: AdminStatsResponse): AdminStats => ({
  tenantCount: data.totalTenants || 0,
  activeTenantCount: data.activeTenants || 0,
  courseCount: data.totalCourses || 0,
  studentCount: data.totalStudents || 0,
  teacherCount: data.totalTeachers || 0,
  lessonCount: data.totalLessons || 0,
  publishedCourseCount: 0, // 后端暂无此数据
  monthlyLessons: data.monthlyLessons || 0,
});

// 趋势数据映射：分离数组 -> 对象数组
const mapTrendData = (data: StatsTrendResponse): TrendData[] => {
  if (!data || !data.dates || data.dates.length === 0) return [];
  return data.dates.map((date, index) => ({
    month: date,
    tenantCount: 0, // 后端无此数据
    lessonCount: data.lessonCounts?.[index] || 0,
    studentCount: data.studentCounts?.[index] || 0,
  }));
};

// 活跃租户数据映射
const mapActiveTenants = (data: ActiveTenantResponse[]): ActiveTenant[] => {
  if (!data || data.length === 0) return [];
  return data.map(item => ({
    id: item.tenantId,
    name: item.tenantName,
    activeTeacherCount: item.activeTeacherCount ?? 0,
    completedLessonCount: item.completedLessonCount ?? 0,
  }));
};

// 热门课程数据映射
const mapPopularCourses = (data: PopularCourseResponse[]): PopularCourse[] => {
  if (!data || data.length === 0) return [];
  return data.map(item => ({
    id: item.courseId,
    name: item.courseName,
    usageCount: item.usageCount,
    teacherCount: item.teacherCount,
  }));
};

export const getAdminStats = async () => {
  const data = await http.get<AdminStatsResponse>('/v1/admin/stats');
  return mapStatsData(data);
};

export const getTrendData = async () => {
  const data = await http.get<StatsTrendResponse>('/v1/admin/stats/trend');
  return mapTrendData(data);
};

export const getActiveTenants = async (limit?: number) => {
  const data = await http.get<ActiveTenantResponse[]>('/v1/admin/stats/tenants/active', { params: { limit } });
  return mapActiveTenants(data);
};

export const getPopularCourses = async (limit?: number) => {
  const data = await http.get<PopularCourseResponse[]>('/v1/admin/stats/courses/popular', { params: { limit } });
  return mapPopularCourses(data);
};

// ==================== 课程套餐 ====================

export const getPublishedPackages = () =>
  http.get<CourseCollectionResponse[]>('/v1/admin/collections/all');

// ==================== 系统设置 ====================

export const getAdminSettings = () =>
  http.get<AdminSettings>('/v1/admin/settings');

export const updateAdminSettings = (data: Record<string, any>) =>
  http.put<AdminSettings>('/v1/admin/settings', data);
