import client from './client'

// ── Types ───────────────────────────────────────────────────────────────────

export interface BugCollectOverview {
  totalIssues: number
  todayNewIssues: number
  affectedUsers: number
  crashRate: number
  crashRateTrend: { date: string; rate: number }[]
  topIssues: { id: string; title: string; level: string; count: number }[]
}

// Matches backend IssueResponse
export interface BugCollectIssue {
  id: number
  appKey: string
  fingerprint?: string
  level: string
  status: string
  title: string
  firstSeenAt: string
  lastSeenAt: string
  count: number
  affectedUsers: number
  assignee?: string
  platform?: string
  release?: string
}

// Matches backend IssueEventResponse.ExceptionInfo
export interface BugCollectExceptionInfo {
  type?: string
  value?: string
  stacktrace?: string
  stackSymbolicated?: string
}

// Matches backend IssueEventResponse
export interface BugCollectEventItem {
  id: number
  issueId?: number
  eventId?: string
  appKey?: string
  userId?: string
  sessionId?: string
  exception?: BugCollectExceptionInfo
  breadcrumbs?: unknown
  tags?: unknown
  device?: unknown
  platform?: string
  release?: string
  environment?: string
  sdkName?: string
  sdkVersion?: string
  createdAt: string
}

// IssueResponse with events embedded (detail view)
export interface BugCollectIssueDetail extends BugCollectIssue {
  events?: BugCollectEventItem[]
}

// Matches backend IssueResponse used for rankings
export interface BugCollectIssueRanking {
  id: number
  title: string
  level: string
  status: string
  platform?: string
  count: number
  affectedUsers: number
  firstSeenAt: string
  lastSeenAt: string
  release?: string
  riskScore?: number
}

export interface BugCollectFunnelStep {
  eventName: string
  count: number
  conversionRate: number
}

export interface BugCollectWebhook {
  id: string
  appKey: string
  url: string
  events: string[]
  cooldownSec: number
  enabled: boolean
  hasSecret: boolean
  createdAt: string
}

export interface BugCollectWebhookRequest {
  appKey: string
  url: string
  events: string[]
  cooldownSec: number
  secret?: string
}

export interface BugCollectSourcemap {
  id: number
  appKey: string
  platform: string
  appVersion: string
  buildId: string | null
  moduleId: string | null
  moduleVersion: string | null
  bundleHash: string | null
  artifactType: 'RN_SOURCEMAP' | 'R8_MAPPING'
  artifactHash: string | null
  contentHash: string
  storageKey: string
  uploadedAt: string
}

export interface BugCollectStatistics {
  levelDistribution: { name: string; value: number }[]
  statusDistribution: { name: string; value: number }[]
  platformDistribution: { name: string; value: number }[]
  versionDistribution: { name: string; value: number }[]
  dailyTrend: { date: string; fatal: number; error: number; warning: number; total: number }[]
}

// Matches backend PageResult<T>
export interface BugCollectPageResult<T> {
  items: T[]
  page: number
  size: number
  total: number
}

// ── API ─────────────────────────────────────────────────────────────────────

export const bugCollectApi = {
  // Overview
  overview: (appKey: string) =>
    client.get<{ data: BugCollectOverview }>('/bugcollect/v1/overview', { params: { appKey } }),

  // Statistics
  statistics: (appKey: string, params?: { from?: string; to?: string }) =>
    client.get<{ data: BugCollectStatistics }>('/bugcollect/v1/statistics', { params: { appKey, ...params } }),

  // Issues — page is 1-based (backend convention); startDate/endDate mapped to from/to
  issues(appKey: string, params: {
    level?: string
    platform?: string
    status?: string
    q?: string
    assignee?: string
    environment?: string
    startDate?: string
    endDate?: string
    page?: number
    size?: number
  }) {
    const { startDate, endDate, page, ...rest } = params
    return client.get<{ data: BugCollectPageResult<BugCollectIssue> }>('/bugcollect/v1/issues', {
      params: { appKey, ...rest, from: startDate, to: endDate, page: (page ?? 0) + 1 },
    })
  },

  issueDetail(id: string | number) {
    return client.get<{ data: BugCollectIssueDetail }>(`/bugcollect/v1/issues/${id}`)
  },

  issueTrend(id: string | number, params?: { from?: string; to?: string }) {
    return client.get<{ data: { issueId: number; points: { date: string; count: number; affectedUsers: number }[] } }>(
      `/bugcollect/v1/issues/${id}/trend`,
      { params },
    )
  },

  resolveIssue(id: string | number) {
    return client.put<{ data: void }>(`/bugcollect/v1/issues/${id}/resolve`)
  },

  ignoreIssue(id: string | number) {
    return client.put<{ data: void }>(`/bugcollect/v1/issues/${id}/ignore`)
  },

  reopenIssue(id: string | number) {
    return client.put<{ data: void }>(`/bugcollect/v1/issues/${id}/reopen`)
  },

  assignIssue(id: string | number, assignee: string) {
    return client.put<{ data: void }>(`/bugcollect/v1/issues/${id}/assign`, { assignee })
  },

  deleteIssue(id: string | number) {
    return client.delete(`/bugcollect/v1/issues/${id}`)
  },

  bulkUpdateIssues(appKey: string, ids: number[], action: string) {
    return client.post<{ data: void }>('/bugcollect/v1/issues/bulk', { ids, action }, { params: { appKey } })
  },

  // Rankings
  frequencyRanking(appKey: string, params?: { from?: string; to?: string; limit?: number }) {
    return client.get<{ data: BugCollectIssueRanking[] }>('/bugcollect/v1/issues/rankings/frequency', {
      params: { appKey, ...params },
    })
  },

  riskRanking(appKey: string, params?: { from?: string; to?: string; limit?: number }) {
    return client.get<{ data: BugCollectIssueRanking[] }>('/bugcollect/v1/issues/rankings/risk', {
      params: { appKey, ...params },
    })
  },

  // Issue events
  issueEvents(id: string | number, params?: { from?: string; to?: string; page?: number; size?: number }) {
    const { page, ...rest } = params ?? {}
    return client.get<{ data: BugCollectPageResult<BugCollectEventItem> }>(`/bugcollect/v1/issues/${id}/events`, {
      params: { ...rest, page: (page ?? 0) + 1 },
    })
  },

  // Analytics events
  events(appKey: string, params: {
    eventName?: string
    userId?: string
    startDate?: string
    endDate?: string
    page?: number
    size?: number
  }) {
    const { eventName, startDate, endDate, page, ...rest } = params
    return client.get<{ data: BugCollectPageResult<BugCollectEventItem> }>('/bugcollect/v1/events', {
      params: { appKey, ...rest, name: eventName, from: startDate, to: endDate, page: (page ?? 0) + 1 },
    })
  },

  // Funnel
  funnel(appKey: string, steps: string[]) {
    return client.get<{ data: BugCollectFunnelStep[] }>('/bugcollect/v1/events/funnel', {
      params: { appKey, steps: steps.join(',') },
    })
  },

  // Webhooks
  webhooks: {
    list: (appKey: string) =>
      client.get<{ data: BugCollectWebhook[] }>('/bugcollect/v1/webhooks', { params: { appKey } }),
    create: (data: BugCollectWebhookRequest) =>
      client.post<{ data: BugCollectWebhook }>('/bugcollect/v1/webhooks', data),
    update: (id: string | number, data: Partial<BugCollectWebhookRequest>) =>
      client.put<{ data: BugCollectWebhook }>(`/bugcollect/v1/webhooks/${id}`, data),
    delete: (id: string | number) =>
      client.delete(`/bugcollect/v1/webhooks/${id}`),
  },

  // Sourcemaps
  sourcemaps: {
    list: (appKey: string) =>
      client.get<{ data: BugCollectSourcemap[] }>('/bugcollect/v1/sourcemaps', { params: { appKey } }),
    delete: (id: number) =>
      client.delete(`/bugcollect/v1/sourcemaps/${id}`),
    pruneAll: () =>
      client.post<{ data: string }>('/bugcollect/v1/sourcemaps/prune-all'),
  },
}
