/**
 * Minimal Cloudflare Workers type stubs for cloud-artifacts Worker.
 *
 * The canonical types are in worker-configuration.d.ts (generated by `wrangler types`,
 * gitignored). This file provides just enough so `tsc --noEmit` passes even when that
 * generated file is absent (e.g. CI, fresh clone).
 */

// -- R2 types ---------------------------------------------------------------

interface R2Checksums {
  readonly md5?: ArrayBuffer
  readonly sha1?: ArrayBuffer
  readonly sha256?: ArrayBuffer
  readonly sha384?: ArrayBuffer
  readonly sha512?: ArrayBuffer
}

interface R2HTTPMetadata {
  contentType?: string
  contentLanguage?: string
  contentDisposition?: string
  contentEncoding?: string
  cacheControl?: string
  cacheExpiry?: Date
}

interface R2Range {
  offset: number
  length?: number
}

declare abstract class R2Object {
  readonly key: string
  readonly version: string
  readonly size: number
  readonly etag: string
  readonly httpEtag: string
  readonly checksums: R2Checksums
  readonly uploaded: Date
  readonly httpMetadata?: R2HTTPMetadata
  readonly customMetadata?: Record<string, string>
  readonly range?: R2Range
  readonly storageClass: string
  readonly ssecKeyMd5?: string
  writeHttpMetadata(headers: Headers): void
}

interface R2ObjectBody extends R2Object {
  get body(): ReadableStream
  get bodyUsed(): boolean
}

interface R2PutOptions {
  httpMetadata?: R2HTTPMetadata | Headers
  customMetadata?: Record<string, string>
}

interface R2Bucket {
  head(key: string): Promise<R2Object | null>
  get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>
  put(
    key: string,
    value:
      | ReadableStream
      | ArrayBuffer
      | ArrayBufferView
      | string
      | null
      | Blob,
    options?: R2PutOptions,
  ): Promise<R2Object>
  delete(keys: string | string[]): Promise<void>
}

// Empty placeholder — R2GetOptions is unused beyond an optional parameter
type R2GetOptions = {}

// -- ExportedHandler -------------------------------------------------------

interface ExportedHandler<Env = unknown> {
  fetch?: (
    request: Request,
    env: Env,
    ctx: ExecutionContext,
  ) => Response | Promise<Response>
}

// -- Env -------------------------------------------------------------------
// Wrangler-generated worker-configuration.d.ts supplies TOKEN via `wrangler secret put`.
// This declaration provides the R2 binding + wrangler vars so the Worker compiles
// without the generated file.
//
// NOTE: 这个文件是脚本（没有 top-level import/export），顶层 interface 自动是 global
// ambient，会和 worker-configuration.d.ts 的 `interface Env` 走 interface declaration
// merging。不要用 `declare global { ... }` 包裹——脚本文件里那种写法是 TS2669 错误，
// 在 .d.ts 里甚至会被静默吞掉，导致 Env 桩完全不生效（CI 上就是这种情况）。
interface Env {
  BUCKET: R2Bucket
  TOKEN: string
  MAX_BYTES: string
  DEFAULT_TTL_DAYS: string
  PUBLIC_URL: string
}
