import client from './client'

export interface App {
  id: string
  tenantId: string
  packageName?: string
  iosBundleId?: string
  harmonyBundleName?: string
  name: string
  description?: string
  iconUrl?: string
  appKey: string
  appSecret: string
  configFileId?: string | null
  configFileRevision?: number | null
  configFileIssuedAt?: string | null
  configFileExpiresAt?: string | null
  createdAt: string
}

export interface ConfigFileMetadata {
  configId: string
  revision: number
  issuedAt: string
  expiresAt: string | null
  longTerm: boolean
}

export interface CreateAppRequest {
  packageName?: string
  iosBundleId?: string
  harmonyBundleName?: string
  name: string
  description?: string
  iconUrl?: string
}

export interface FeatureService {
  id: string
  appKey: string
  platform: 'ANDROID' | 'IOS' | 'HARMONY'
  serviceType: 'IM' | 'PUSH' | 'UPDATE' | 'BUG_COLLECT'
  enabled: boolean
  config?: string | null
  createdAt: string
}

export interface ImServiceConfig {
  allowStrangerMessage: boolean
  allowFriendRequest: boolean
  friendRequestMode: 'REQUIRE_CONFIRM' | 'DIRECT_ACCEPT' | 'DISALLOW'
  allowGroupJoinRequest: boolean
  blacklistSendSuccess: boolean
  messageRecallMinutes: number
  historyRetentionDays: number
  conversationPullLimit: number
  multiClientConversationDeleteSync: boolean
  multiDeviceLoginMode?: 'MULTI_DEVICE_FREE' | 'SAME_PLATFORM_ONE' | 'SINGLE_DEVICE'
}

export interface UpdateServiceConfig {
  defaultStoreTargets?: string[]
  defaultPublishMode?: 'MANUAL' | 'NOW' | 'SCHEDULED' | 'AUTO_REVIEW'
  defaultPublishImmediately?: boolean
  defaultScheduledPublishAt?: string
  defaultAutoPublishAfterReview?: boolean
  defaultWebhookUrl?: string
  defaultForceUpdate?: boolean
  defaultGrayEnabled?: boolean
  defaultGrayPercent?: number
  defaultPackageName?: string
  defaultAppStoreUrl?: string
  defaultMarketUrl?: string
}

export type PushVendorKey = 'huawei' | 'xiaomi' | 'oppo' | 'vivo' | 'honor' | 'harmony' | 'apns'
export type PushImportance = 'MIN' | 'LOW' | 'DEFAULT' | 'HIGH' | 'MAX'
export type PushPriority = 'LOW' | 'DEFAULT' | 'HIGH'
export type PushInterruptionLevel = '' | 'passive' | 'active' | 'time-sensitive' | 'critical'

export interface XiaomiPushVendorConfig {
  appId?: string
  appKey?: string
  appSecret?: string
}

export interface HuaweiPushVendorConfig {
  appId?: string
  appSecret?: string
}

export interface OppoPushVendorConfig {
  appId?: string
  appKey?: string
  appSecret?: string
  masterSecret?: string
}

export interface VivoPushVendorConfig {
  appId?: string
  appKey?: string
  appSecret?: string
}

export interface HonorPushVendorConfig {
  appId?: string
  clientId?: string
  clientSecret?: string
}

export interface HarmonyPushVendorConfig {
  appId?: string
  appSecret?: string
}

export interface ApnsPushVendorConfig {
  teamId?: string
  keyId?: string
  bundleId?: string
  privateKey?: string
  sandbox?: boolean
}

export interface PushVendorsConfig {
  huawei?: HuaweiPushVendorConfig
  xiaomi?: XiaomiPushVendorConfig
  oppo?: OppoPushVendorConfig
  vivo?: VivoPushVendorConfig
  honor?: HonorPushVendorConfig
  harmony?: HarmonyPushVendorConfig
  apns?: ApnsPushVendorConfig
}

export interface PushProfileConfig {
  profileKey: string
  vendor: PushVendorKey
  routeType: string
  enabled: boolean
  channelId?: string
  category?: string
  importance?: PushImportance
  priority?: PushPriority
  threadIdentifier?: string
  interruptionLevel?: PushInterruptionLevel
  badge?: boolean
  sound?: boolean
  vibration?: boolean
  notifyType?: number
  version?: number
  remark?: string
}

export interface PushServiceConfig {
  schemaVersion?: number
  updatedAt?: string
  vendors?: PushVendorsConfig
  profiles?: PushProfileConfig[]
}

export const appApi = {
  list: () => client.get<{ data: App[] }>('/apps'),

  get: (appKey: string) => client.get<{ data: App }>(`/apps/${appKey}`),

  create: (data: CreateAppRequest) => client.post<{ data: App }>('/apps', data),

  update: (appKey: string, data: CreateAppRequest) => client.put<{ data: App }>(`/apps/${appKey}`, data),

  delete: (appKey: string) => client.delete(`/apps/${appKey}`),

  getServices: (appKey: string) =>
    client.get<{ data: FeatureService[] }>(`/apps/${appKey}/services`),

  getService: async (appKey: string, platform: string, serviceType: string) => {
    const res = await client.get<{ data: FeatureService[] }>(`/apps/${appKey}/services`)
    const service = res.data.data.find(item => item.platform === platform && item.serviceType === serviceType)
    if (!service) {
      throw new Error('服务不存在')
    }
    return {
      ...res,
      data: { data: service },
    } as typeof res & { data: { data: FeatureService } }
  },

  getServiceItem: (appKey: string, platform: string, serviceType: string) =>
    client.get<{ data: FeatureService }>(`/apps/${appKey}/services/item`, {
      params: { platform, serviceType },
    }),

  toggleService: (appKey: string, platform: string, serviceType: string, enable: boolean) =>
    client.post<{ data: FeatureService }>(`/apps/${appKey}/services/toggle`, null, {
      params: { platform, serviceType, enable },
    }),

  updateServiceConfig: (
    appKey: string,
    platform: string,
    serviceType: string,
    config: Partial<ImServiceConfig> & Partial<UpdateServiceConfig> & Partial<PushServiceConfig> | Record<string, unknown>,
  ) =>
    client.put<{ data: FeatureService }>(`/apps/${appKey}/services/config`, config, {
      params: { platform, serviceType },
    }),

  requestSecretVerify: (appKey: string, purpose: 'REVEAL_SECRET' | 'RESET_SECRET') =>
    client.post<{ data: null }>(`/apps/${appKey}/request-secret-verify`, null, {
      params: { purpose },
    }),

  revealSecret: (appKey: string, code: string) =>
    client.post<{ data: { appSecret: string } }>(`/apps/${appKey}/reveal-secret`, { code }),

  resetSecret: (appKey: string, code: string) =>
    client.post<{ data: { appSecret: string } }>(`/apps/${appKey}/reset-secret`, { code }),

  downloadConfigFile: (appKey: string) =>
    client.get<Blob>(`/apps/${appKey}/config-file`, { responseType: 'blob' }),

  regenerateConfigFile: (appKey: string, data: { longTerm: boolean; expiresAt: string | null }) =>
    client.post<{ data: ConfigFileMetadata }>(`/apps/${appKey}/config-file/regenerate`, data),

  requestActivation: (appKey: string, serviceType: 'IM' | 'PUSH' | 'UPDATE' | 'BUG_COLLECT', reason: string) =>
    client.post<{ data: null }>(`/apps/${appKey}/services/request-activation`, null, {
      params: { platform: 'ANDROID', serviceType, applyReason: reason },
    }),

  parseConfigFile: (content: string) =>
    client.post<{ data: { schemaVersion: number; configId: string; revision: number; issuedAt: string; expiresAt: string | null; appKey: string; appName: string; packageName: string; iosBundleId: string; harmonyBundleName: string; serverUrl: string } }>(
      '/apps/config/parse',
      { content },
    ),
}
