// 在全局注册Headers（如果不存在）
if (typeof globalThis.Headers === 'undefined') {
  // 这里会由headers-polyfill.js注册
}

// Response 类型枚举
type ResponseType = 'basic' | 'cors' | 'default' | 'error' | 'opaque' | 'opaqueredirect'

export class ResponsePolyfill {
  // 标准 Response 接口的额外属性（小程序环境简化实现）
  readonly redirected: boolean = false
  readonly type: ResponseType = 'basic'
  readonly url: string = ''

  constructor(
    public body: string | ArrayBuffer | null,
    public init: {
      status?: number
      statusText?: string
      headers?: Record<string, string>
      url?: string
    } = {}
  ) {
    if (init.url) {
      this.url = init.url
    }
  }

  get ok(): boolean {
    return this.status >= 200 && this.status < 300
  }

  get status(): number {
    return this.init.status || 200
  }

  get statusText(): string {
    return this.init.statusText || 'OK'
  }

  get headers(): Headers {
    return new Headers(this.init.headers || {})
  }

  get bodyUsed(): boolean {
    return false // 小程序环境简单实现
  }

  // bytes() 是一个返回 Promise<Uint8Array> 的方法（较新的 Web API）
  async bytes(): Promise<Uint8Array> {
    if (this.body instanceof ArrayBuffer) {
      return new Uint8Array(this.body)
    }
    if (typeof this.body === 'string') {
      // 将字符串转为 Uint8Array
      const encoder = new TextEncoder()
      return encoder.encode(this.body)
    }
    throw new Error('No body available')
  }

  async arrayBuffer(): Promise<ArrayBuffer> {
    if (this.body instanceof ArrayBuffer) {
      return this.body
    }
    throw new Error('Not implemented')
  }

  async blob(): Promise<Blob> {
    // 小程序环境不支持 Blob，抛出错误
    throw new Error('Blob is not supported in mini program environment')
  }

  async formData(): Promise<FormData> {
    // 小程序环境不支持 FormData，抛出错误
    throw new Error('FormData is not supported in mini program environment')
  }

  async text(): Promise<string> {
    if (typeof this.body === 'string') {
      return this.body
    }
    throw new Error('Not implemented')
  }

  async json<T = unknown>(): Promise<T> {
    if (typeof this.body === 'string') {
      try {
        return JSON.parse(this.body)
      } catch {
        throw new Error('Invalid JSON')
      }
    }
    throw new Error('Not implemented')
  }

  clone(): this {
    return new ResponsePolyfill(this.body, { ...this.init }) as this
  }

  static json(data: unknown, init?: ResponseInit): ResponsePolyfill {
    const headers = new Headers(init && 'headers' in init ? init.headers : undefined)
    if (!headers.has('Content-Type')) {
      headers.set('Content-Type', 'application/json')
    }
    // Headers.raw() 是非标准 API，某些实现（如 node-fetch）提供此方法
    const headersWithRaw = headers as { raw?: () => Record<string, string> }
    const headersRecord = typeof headersWithRaw.raw === 'function'
      ? headersWithRaw.raw()
      : {}
    return new ResponsePolyfill(JSON.stringify(data), {
      ...init,
      headers: headersRecord
    })
  }

  static error(): ResponsePolyfill {
    return new ResponsePolyfill(null, { status: 0, statusText: 'Network Error' })
  }

  static redirect(url: string, status: number): ResponsePolyfill {
    return new ResponsePolyfill(null, {
      status,
      headers: { Location: url }
    })
  }
}

// 可选的全局注册函数
export function registerGlobalResponsePolyfill(): void {
  if (typeof globalThis.Response === 'undefined') {
    // @ts-expect-error - 全局类型赋值
    globalThis.Response = ResponsePolyfill
  }
}
