import { get, post, put, del, patch, uploadFile } from '@/utils/request'

export interface User {
  id: number
  username: string
  email: string
  avatar?: string
  bio?: string
  role: string
  isActive?: number
  phone?: string
  wechat?: string
  wechatQrcode?: string
  [key: string]: unknown
}

export interface LoginResponse {
  token: string
  user: User
  expire: number
}

export interface PaginationResponse<T> {
  list: T[]
  total: number
  page: number
  pageSize: number
}

export interface Post {
  id: number | string
  title: string
  content?: string
  summary?: string
  excerpt?: string
  cover?: string
  date?: string
  categoryId?: number
  categoryName?: string
  columnId?: number
  columnName?: string
  userName?: string
  userAvatar?: string
  userId?: number
  readCount?: number
  isPublished?: number | boolean
  tags?: { id: number, name: string }[]
  [key: string]: unknown
}

export interface WorkLinks {
  live?: string
  demo?: string
  github?: string
  [key: string]: unknown
}

export interface WorkTechGroup {
  category?: string
  items?: string[]
  [key: string]: unknown
}

export interface Work {
  id: string
  title: string
  category?: string
  year?: string
  heroImg?: string
  heroVideo?: string
  /** API 字段名为 desc */
  desc?: string
  description?: string
  videoUrl?: string
  videoId?: number | string
  techStack?: WorkTechGroup[]
  gallery?: string[]
  links?: WorkLinks | string
  next?: string
  [key: string]: unknown
}

export interface Column {
  id: number | string
  title?: string
  name?: string
  description?: string
  cover?: string
  postCount?: number
  isActive?: number | boolean
  sortOrder?: number
  [key: string]: unknown
}

export interface Snippet {
  id: number | string
  title: string
  code?: string
  language?: string
  description?: string
  codeTypeId?: number
  postIds?: number[]
  [key: string]: unknown
}

export interface VideoItem {
  id: string
  title: string
  cover?: string
  poster?: string
  videoUrl?: string
  url?: string
  description?: string
  categoryId?: number
  categoryName?: string
  albumIds?: number[]
  isPublished?: number | boolean
  duration?: number
  createdAt?: string
  [key: string]: unknown
}

export interface VideoAlbumNavContext {
  albumId: number
  albumName: string
  prevVideos: VideoItem[]
  nextVideos: VideoItem[]
}

export interface VideoDetailItem extends VideoItem {
  albumContext?: VideoAlbumNavContext
}

export interface VideoAlbum {
  id: number
  name: string
  description?: string
  cover?: string
  categoryId?: number
  categoryName?: string
  videoCount?: number
  videoIds?: number[]
  isActive?: number | boolean
  sortOrder?: number
  latestVideoUpdatedAt?: string
  previewVideos?: VideoItem[]
  [key: string]: unknown
}

export interface AboutExperience {
  year?: string
  role?: string
  company?: string
}

export interface AboutProfile {
  id?: number
  name?: string
  avatar?: string
  location?: string
  bio?: string
  email?: string
  wechat?: string
  isPrimary?: number | boolean
  techStack?: string[]
  experiences?: AboutExperience[]
  role?: string
  [key: string]: unknown
}

export interface Attachment {
  id: number
  originalName?: string
  fileName?: string
  fileUrl?: string
  url?: string
  fileType?: string
  fileSize?: number
  categoryId?: number
  [key: string]: unknown
}

export interface Inquiry {
  id: number
  name?: string
  company?: string
  contactMethod?: string
  contactValue?: string
  budget?: string
  description?: string
  status?: number
  createdAt?: string
  [key: string]: unknown
}

// ---- Auth ----
export const loginApi = (username: string, password: string) =>
  post<LoginResponse>('/admin/login', { username, password })

export const wxLoginApi = (code: string) =>
  post<LoginResponse>('/auth/wx-login', { code })

/** 游客合并到管理员：需携带游客 JWT */
export const mergeAccountApi = (username: string, password: string) =>
  post<LoginResponse>('/auth/merge-account', { username, password }, true)

export const getCurrentUser = () => get<User>('/admin/me', undefined, true)

/** 更新当前登录用户资料 */
export const updateMe = (data: Partial<User>) => put<User>('/admin/me', data, true)

export const updatePassword = (oldPassword: string, newPassword: string) =>
  put('/admin/me/password', { oldPassword, newPassword }, true)

// ---- Public ----
export const getPublicSettings = () => get<Record<string, string>>('/settings')

export const getPosts = (params: Record<string, unknown> = {}) =>
  get<PaginationResponse<Post> | Post[]>('/posts', params)

export const getPost = (id: string | number) => get<Post>(`/posts/${id}`)

export const getRecommendedPosts = (id: string | number, limit = 3) =>
  get<Post[]>(`/posts/${id}/recommendations`, { limit })

export const getHotSearches = (limit = 10) => get<{ keyword: string, count: number }[]>('/search/hot', { limit })

export const getColumns = () => get<Column[]>('/columns')
export const getColumn = (id: string | number) => get<Column>(`/columns/${id}`)
export const getColumnPosts = (id: string | number) => get<Post[]>(`/columns/${id}/posts`)

export const getWorks = () => get<Work[]>('/works')
export const getWork = (id: string) => get<Work>(`/works/${id}`)

export const getSnippets = () => get<Snippet[]>('/snippets')
export const getSnippet = (id: string | number) => get<Snippet>(`/snippets/${id}`)

export const getVideoCategories = () => get<unknown[]>('/video-categories')
export const getVideoAlbums = (params: Record<string, unknown> = {}) =>
  get<VideoAlbum[]>('/video-albums', params)
export const getVideoAlbum = (id: string | number) => get<VideoAlbum>(`/video-albums/${id}`)
export const getVideos = (params: Record<string, unknown> = {}) => get<VideoItem[]>('/videos', params)
export const getVideo = (id: string) => get<VideoDetailItem>(`/videos/${id}`)
export const getAlbumVideos = (id: string | number) => get<VideoItem[]>(`/video-albums/${id}/videos`)

export const getAbout = () => get<AboutProfile | AboutProfile[]>('/about')
export const getTestimonials = () => get<unknown[]>('/testimonials')
export const getPartners = () => get<unknown[]>('/partners')
export const getEmailSuffixes = () => get<string[]>('/email-suffixes')
export const submitInquiry = (data: Record<string, unknown>) => post('/inquiries', data)

export const getCategories = () => get<{ id: number, name: string }[]>('/categories')
export const getTags = () => get<{ id: number, name: string }[]>('/tags')

/** 仪表盘趋势点（后端 date + value；兼容旧 count 字段） */
export interface TrendPoint {
  date: string
  value?: number
  count?: number
  yoy?: number
  mom?: number
}

/** 读取趋势点数值：优先 value，兼容 SQL/旧接口的 count */
export function trendPointValue(p?: TrendPoint | null): number {
  if (!p) return 0
  return Number(p.value ?? p.count ?? 0)
}

/** 热门文章排行项：后端访问统计返回 count，兼容文章实体上的 readCount */
export interface DashboardTopPost {
  title?: string
  article_id?: number
  count?: number
  readCount?: number
  [key: string]: unknown
}

/** 概览结构化统计，对应 GetDashboardStats */
export interface DashboardStats {
  posts?: number
  works?: number
  inquiryCount?: number
  postsTrend?: TrendPoint[]
  uvTrend?: TrendPoint[]
  topPosts?: DashboardTopPost[]
  operationTrend?: TrendPoint[]
  userRegions?: { region?: string, name?: string, count?: number, value?: number }[]
}

// ---- Admin dashboard ----
export const getDashboardStats = (params: Record<string, unknown> = {}) =>
  get<DashboardStats>('/admin/dashboard/stats', params, true)
export const getRecentActivities = () => get<unknown[]>('/admin/dashboard/activities', undefined, true)
export const getOperationLogs = (page = 1, pageSize = 10, filters: Record<string, unknown> = {}) =>
  get<PaginationResponse<unknown>>('/admin/operation-logs', { page, pageSize, ...filters }, true)
export const getAccessLogs = (page = 1, pageSize = 10, filters: Record<string, unknown> = {}) =>
  get<PaginationResponse<unknown>>('/admin/access-logs', { page, pageSize, ...filters }, true)

// ---- Admin posts extras ----
/** 切换文章发布状态 */
export const patchPostStatus = (id: string | number, isPublished: number) =>
  patch(`/admin/posts/${id}/status`, { isPublished }, true)

export const patchPostRelations = (id: string | number, data: Record<string, unknown>) =>
  patch(`/admin/posts/${id}/relations`, data, true)

export const getPostHistory = (id: string | number) =>
  get<unknown[]>(`/admin/posts/${id}/history`, undefined, true)

/** 后台文章详情（含未发布），编辑表单专用；勿用公开 getPost */
export const adminGetPost = (id: string | number) =>
  get<Post>(`/admin/posts/${id}`, undefined, true)

export const restorePostVersion = (id: string | number, version: string | number) =>
  post(`/admin/posts/${id}/history/${version}/restore`, {}, true)

export const getPostAccessLogs = (id: string | number, params: Record<string, unknown> = {}) =>
  get<PaginationResponse<unknown>>(`/admin/posts/${id}/access-logs`, params, true)

// ---- Admin inquiries ----
export const updateInquiryStatus = (id: string | number, status: number) =>
  put(`/admin/inquiries/${id}/status`, { status }, true)

// ---- Admin columns posts ----
export const addPostToColumn = (columnId: string | number, postId: string | number) =>
  post(`/admin/columns/${columnId}/posts`, { postId }, true)

export const removePostFromColumn = (columnId: string | number, postId: string | number) =>
  del(`/admin/columns/${columnId}/posts/${postId}`, true)

export const getAdminColumnPosts = (columnId: string | number) =>
  get<Post[]>(`/admin/columns/${columnId}/posts`, undefined, true).catch(() => getColumnPosts(columnId))

// ---- Admin video albums ----
export const getAlbumVideoIds = (id: string | number) =>
  get<number[]>(`/admin/video-albums/${id}/video-ids`, undefined, true)

// ---- Admin attachments ----
export const uploadAttachment = (filePath: string, formData: Record<string, string> = {}) =>
  uploadFile<Attachment>('/admin/attachments/upload', filePath, formData)

// ---- Admin settings ----
export const getAdminSettings = () => get<unknown>('/admin/settings', undefined, true)
export const batchUpdateSettings = (values: Record<string, string>) =>
  put('/admin/settings', values, true)

// ---- Admin OSS ----
export const testOssConfig = (id: string | number) =>
  post<{ storageType: string, name: string }>(`/admin/oss-configs/${id}/test`, {}, true)

// ---- Admin generic CRUD helpers ----
const RESOURCE_ALIAS: Record<string, string> = {
  logs: 'operation-logs',
  'access-logs': 'access-logs',
  about: 'about',
  settings: 'settings',
}

function adminPath(resource: string, id?: string | number) {
  const name = RESOURCE_ALIAS[resource] || resource
  return id != null ? `/admin/${name}/${id}` : `/admin/${name}`
}

export function adminList(resource: string, params: Record<string, unknown> = {}) {
  return get<unknown>(adminPath(resource), params, true)
}

export function adminGet(resource: string, id: string | number) {
  return get<unknown>(adminPath(resource, id), undefined, true)
}

export function adminCreate(resource: string, data: unknown) {
  return post(adminPath(resource), data, true)
}

export function adminUpdate(resource: string, id: string | number, data: unknown) {
  return put(adminPath(resource, id), data, true)
}

export function adminDelete(resource: string, id: string | number) {
  return del(adminPath(resource, id), true)
}

/** 统一把列表接口结果规范成数组（兼容 list 包装与裸数组） */
export function normalizeAdminList<T = Record<string, unknown>>(data: unknown): T[] {
  if (Array.isArray(data)) return data as T[]
  if (data && typeof data === 'object' && Array.isArray((data as { list?: unknown[] }).list)) {
    return (data as { list: T[] }).list
  }
  return []
}

/** 统一分页结构 */
export function normalizePagination<T = Record<string, unknown>>(
  data: unknown,
  page = 1,
  pageSize = 20,
): PaginationResponse<T> {
  if (data && typeof data === 'object' && Array.isArray((data as PaginationResponse<T>).list)) {
    const p = data as PaginationResponse<T>
    return {
      list: p.list,
      total: Number(p.total ?? p.list.length),
      page: Number(p.page ?? page),
      pageSize: Number(p.pageSize ?? pageSize),
    }
  }
  const list = normalizeAdminList<T>(data)
  return { list, total: list.length, page, pageSize }
}
