import api from '../utils/request'

export interface Application {
  id: number
  app_id: string
  owner_id: number
  app_name: string
  icon_url?: string
  /** MinIO object key，编辑提交时用 */
  icon_object_key?: string | null
  protocol_type: 'OIDC' | 'SIMPLE_API' | 'NONE'
  redirect_uris?: string
  notification_url?: string
  description?: string
  category_id?: number
  category_name?: string
  created_at: string
}

export interface ApplicationCreate {
  app_name: string
  icon_url?: string
  protocol_type: 'OIDC' | 'SIMPLE_API' | 'NONE'
  redirect_uris?: string
  notification_url?: string
  description?: string
  category_id?: number
  password?: string
  verification_code?: string
}

export interface AppSecretResponse {
  app_id: string
  app_secret: string
  access_token: string
}

export interface ApplicationListResponse {
  total: number
  items: Application[]
}

export interface MappingResponse {
  id: number
  app_id: number
  user_id: number
  mapped_key: string
  mapped_email?: string
  user_name?: string
  user_mobile: string
  user_status: string // Added
  is_active: boolean
  new_user_created?: boolean
  generated_password?: string
}

export interface MappingListResponse {
  total: number
  items: MappingResponse[]
}

// Logs
export interface OperationLog {
    id: number
    app_id: number
    action_type:
        | 'MANUAL_ADD'
        | 'DELETE'
        | 'UPDATE'
        | 'IMPORT'
        | 'TRANSFER'
        | 'VIEW_SECRET'
        | 'REGENERATE_SECRET'
        | 'SYNC'
        | 'SYNC_M2M'
        | 'DISABLE'
        | 'ENABLE'
        | 'RESET_PASSWORD'
        | 'CHANGE_ROLE'
    target_mobile?: string
    operator_mobile?: string
    ip_address?: string
    details?: any
    created_at: string
}

export interface LogListResponse {
    total: number
    items: OperationLog[]
}

export interface LogQueryParams {
    skip: number
    limit: number
    action_type?: string
    keyword?: string
    start_date?: string
    end_date?: string
}

export const uploadAppIcon = (file: File, applicationDbId: number) => {
  const fd = new FormData()
  fd.append('file', file)
  fd.append('app_id', String(applicationDbId))
  return api.post<{ object_key: string }>('/apps/icon/upload', fd)
}

export const getApps = (skip = 0, limit = 10, search = '', categoryId?: number) => {
  const params: any = { skip, limit }
  if (search) {
    params.search = search
  }
  if (categoryId !== undefined) {
    params.category_id = categoryId
  }
  return api.get<ApplicationListResponse>('/apps/', { params })
}

export const getApp = (id: number) => {
  return api.get<Application>(`/apps/${id}`)
}

export const createApp = (data: ApplicationCreate) => {
  return api.post<AppSecretResponse>('/apps/', data)
}

export const updateApp = (id: number, data: Partial<ApplicationCreate>) => {
  return api.put<Application>(`/apps/${id}`, data)
}

export const transferApp = (id: number, data: { target_mobile: string, password: string, verification_code: string }) => {
  return api.post<Application>(`/apps/${id}/transfer`, data)
}

export const deleteApp = (id: number) => {
  return api.delete<Application>(`/apps/${id}`)
}

export const regenerateSecret = (id: number, data: { password: string, verification_code: string }) => {
  return api.post<AppSecretResponse>(`/apps/${id}/regenerate-secret`, data)
}

export const viewSecret = (id: number, password: string) => {
  return api.post<AppSecretResponse>(`/apps/${id}/view-secret`, { password })
}

// Mappings
export interface GetMappingsFilters {
  search?: string
  mapping_is_active?: boolean | null
  user_status?: string
}

export const getMappings = (
  appId: number,
  skip = 0,
  limit = 10,
  filters?: GetMappingsFilters
) => {
  const params: Record<string, string | number | boolean> = { skip, limit }
  if (filters) {
    if (filters.search !== undefined && filters.search.trim() !== '') {
      params.search = filters.search.trim()
    }
    if (filters.mapping_is_active === true || filters.mapping_is_active === false) {
      params.mapping_is_active = filters.mapping_is_active
    }
    if (filters.user_status !== undefined && filters.user_status.trim() !== '') {
      params.user_status = filters.user_status.trim()
    }
  }
  return api.get<MappingListResponse>(`/apps/${appId}/mappings`, { params })
}

export const createMapping = (appId: number, data: { mobile: string, mapped_key?: string, mapped_email?: string, password: string }) => {
  return api.post<MappingResponse>(`/apps/${appId}/mappings`, data)
}

export const updateMapping = (
  appId: number,
  mappingId: number,
  data: { mapped_key?: string; mapped_email?: string; is_active?: boolean; password: string }
) => {
  return api.put<MappingResponse>(`/apps/${appId}/mappings/${mappingId}`, data)
}

export const deleteMapping = (appId: number, mappingId: number, password: string) => {
  return api.delete(`/apps/${appId}/mappings/${mappingId}`, { data: { password } })
}

export const exportMappings = (appId: number) => {
  return api.get(`/apps/${appId}/mappings/export`, { responseType: 'blob' })
}

export const syncAppUsers = (appId: number) => {
  return api.post<{ message: string }>(`/apps/${appId}/sync-users`)
}

export interface AppSyncRequest {
    mode: 'ALL' | 'SELECTED'
    user_ids?: number[]
    init_email: boolean
    email_domain?: string
    verification_code: string
}

export const syncAppUsersV2 = (appId: number, data: AppSyncRequest) => {
  return api.post<{ message: string }>(`/apps/${appId}/sync-users-v2`, data)
}

export const getOperationLogs = (appId: number, params: LogQueryParams) => {
    return api.get<LogListResponse>(`/apps/${appId}/logs`, { params })
}

// Category Management
export interface CategoryStats {
  category_id: number
  category_name: string
  app_count: number
}

export const getCategories = (search = '') => {
  const params: any = {}
  if (search && search.trim()) {
    params.search = search.trim()
  }
  return api.get<CategoryStats[]>('/apps/categories', { params })
}

export const deleteCategory = (categoryId: number, verificationCode: string) => {
  return api.delete<{ message: string }>(`/apps/categories/${categoryId}`, { 
    params: { verification_code: verificationCode } 
  })
}

// Preset Category Management
export interface AppCategory {
  id: number
  name: string
  description?: string
  created_at: string
  updated_at: string
}

export interface AppCategoryCreate {
  name: string
  description?: string
}

export interface AppCategoryUpdate {
  name?: string
  description?: string
  password?: string  // 编辑时需要密码验证
}

export const getPresetCategories = () => {
  return api.get<AppCategory[]>('/apps/preset-categories')
}

export const createPresetCategory = (data: AppCategoryCreate) => {
  return api.post<AppCategory>('/apps/preset-categories', data)
}

export const updatePresetCategory = (id: number, data: AppCategoryUpdate) => {
  return api.put<AppCategory>(`/apps/preset-categories/${id}`, data)
}

export const deletePresetCategory = (id: number) => {
  return api.delete<{ message: string }>(`/apps/preset-categories/${id}`)
}

// 获取分类下的应用列表
export const getCategoryApps = (categoryId: number, skip = 0, limit = 100) => {
  return api.get<ApplicationListResponse>(`/apps/categories/${categoryId}/apps`, {
    params: { skip, limit }
  })
}

// 批量更新应用分类
export interface BatchUpdateCategoryRequest {
  app_ids: number[]
  category_id?: number | null
  password: string  // 管理员密码验证
}

export const batchUpdateAppCategory = (data: BatchUpdateCategoryRequest) => {
  return api.post<{ message: string; count: number }>('/apps/categories/batch-update', data)
}
