/**
 * 营销活动管理模块属性测试
 * 
 * 使用 fast-check 进行属性测试，验证营销活动管理模块的正确性属性
 * 
 * Feature: marketing-management-frontend
 */

import { describe, it, expect } from 'vitest'
import * as fc from 'fast-check'
import { AdvertJumpType } from './advert'

// ==================== 辅助函数 ====================

/**
 * 构建搜索参数对象，过滤掉空值
 * 用于验证搜索参数正确传递
 */
function buildSearchParams<T extends Record<string, any>>(params: T): Record<string, any> {
  const result: Record<string, any> = {}
  for (const [key, value] of Object.entries(params)) {
    if (value !== undefined && value !== null && (typeof value !== 'string' || value !== '')) {
      result[key] = value
    }
  }
  return result
}

/**
 * 检查值是否为空（undefined, null, 或空字符串）
 */
function isEmptyValue(value: unknown): boolean {
  return value === undefined || value === null || (typeof value === 'string' && value === '')
}

/**
 * 验证分页参数是否有效
 */
function isValidPagination(page: number, pageSize: number): boolean {
  return page >= 1 && pageSize > 0 && Number.isInteger(page) && Number.isInteger(pageSize)
}

/**
 * 验证优惠券表单必填字段
 */
function isValidCouponForm(title: string, minPrice: number, discountPrice: number, validDays: number): boolean {
  return (
    title.trim().length > 0 &&
    typeof minPrice === 'number' && minPrice >= 0 &&
    typeof discountPrice === 'number' && discountPrice > 0 &&
    typeof validDays === 'number' && validDays > 0 && Number.isInteger(validDays)
  )
}

/**
 * 验证广告表单必填字段
 */
function isValidAdvertForm(imageUrl: string, typeId: number): boolean {
  return imageUrl.trim().length > 0 && typeof typeId === 'number' && typeId > 0
}

/**
 * 验证广告类型表单必填字段
 */
function isValidAdvertTypeForm(name: string): boolean {
  return name.trim().length > 0
}

/**
 * 验证排行榜奖品表单必填字段
 */
function isValidRankPrizeForm(rank: number, title: string, imgUrl: string, price: number): boolean {
  return (
    typeof rank === 'number' && rank > 0 && Number.isInteger(rank) &&
    title.trim().length > 0 &&
    imgUrl.trim().length > 0 &&
    typeof price === 'number' && price >= 0
  )
}

/**
 * 根据跳转类型获取应该显示的字段
 */
function getVisibleFieldsByJumpType(jumpType: number): { showCouponId: boolean; showGoodsId: boolean; showUrlLink: boolean } {
  return {
    showCouponId: jumpType === AdvertJumpType.Coupon,
    showGoodsId: jumpType === AdvertJumpType.YiFanShang || jumpType === AdvertJumpType.WuXianShang || jumpType === AdvertJumpType.LianJiShang,
    showUrlLink: jumpType === AdvertJumpType.CustomUrl
  }
}

/**
 * 验证API响应格式是否符合规范
 */
function isValidApiResponse(response: any): boolean {
  return (
    typeof response === 'object' &&
    response !== null &&
    typeof response.code === 'number' &&
    typeof response.message === 'string'
  )
}

/**
 * 验证成功响应格式
 */
function isValidSuccessResponse(response: any): boolean {
  return isValidApiResponse(response) && response.code === 0
}

/**
 * 验证错误响应格式
 */
function isValidErrorResponse(response: any): boolean {
  return (
    isValidApiResponse(response) &&
    response.code !== 0 &&
    response.message.length > 0
  )
}

// ==================== 生成器 ====================

/** 生成可选的关键词 */
const optionalKeywordArb = fc.option(
  fc.string({ minLength: 1, maxLength: 50 }),
  { nil: undefined }
)

/** 生成可选的用户ID */
const optionalUserIdArb = fc.option(fc.integer({ min: 1, max: 999999 }), { nil: undefined })

/** 生成可选的手机号 */
const optionalMobileArb = fc.option(
  fc.stringOf(fc.constantFrom('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), { minLength: 11, maxLength: 11 }),
  { nil: undefined }
)

/** 生成可选的优惠券类型 */
const optionalCouponTypeArb = fc.option(fc.integer({ min: 1, max: 3 }), { nil: undefined })

/** 生成可选的优惠券领取状态 */
const optionalCouponStatusArb = fc.option(fc.integer({ min: 0, max: 2 }), { nil: undefined })

/** 生成可选的广告类型ID */
const optionalAdvertTypeIdArb = fc.option(fc.integer({ min: 1, max: 100 }), { nil: undefined })

/** 生成可选的优惠券标题 */
const optionalTitleArb = fc.option(fc.string({ minLength: 1, maxLength: 50 }), { nil: undefined })

/** 生成有效的页码 */
const validPageArb = fc.integer({ min: 1, max: 1000 })

/** 生成有效的页大小 */
const validPageSizeArb = fc.integer({ min: 1, max: 100 })

/** 生成无效的页码（小于1或非整数） */
const invalidPageArb = fc.oneof(
  fc.integer({ min: -100, max: 0 }),
  fc.double({ min: Math.fround(0.1), max: Math.fround(10), noNaN: true }).filter(n => !Number.isInteger(n))
)

/** 生成无效的页大小（小于等于0或非整数） */
const invalidPageSizeArb = fc.oneof(
  fc.integer({ min: -100, max: 0 }),
  fc.double({ min: Math.fround(0.1), max: Math.fround(10), noNaN: true }).filter(n => !Number.isInteger(n))
)

/** 生成有效的优惠券标题 */
const validCouponTitleArb = fc.string({ minLength: 1, maxLength: 50 }).filter(s => s.trim().length > 0)

/** 生成有效的金额 */
const validPriceArb = fc.float({ min: Math.fround(0), max: Math.fround(10000), noNaN: true })

/** 生成有效的折扣金额（必须大于0） */
const validDiscountPriceArb = fc.float({ min: Math.fround(0.01), max: Math.fround(10000), noNaN: true })

/** 生成有效的天数 */
const validDaysArb = fc.integer({ min: 1, max: 365 })

/** 生成空或纯空白字符串 */
const emptyOrWhitespaceArb = fc.oneof(
  fc.constant(''),
  fc.stringOf(fc.constantFrom(' ', '\t', '\n', '\r'), { minLength: 1, maxLength: 10 })
)

/** 生成有效的图片URL */
const validImageUrlArb = fc.webUrl().filter(url => url.trim().length > 0)

/** 生成有效的广告类型ID */
const validTypeIdArb = fc.integer({ min: 1, max: 100 })

/** 生成有效的广告类型名称 */
const validTypeNameArb = fc.string({ minLength: 1, maxLength: 30 }).filter(s => s.trim().length > 0)

/** 生成有效的排名 */
const validRankArb = fc.integer({ min: 1, max: 100 })

/** 生成广告跳转类型 */
const jumpTypeArb = fc.integer({ min: 0, max: 5 })

/** 生成用户排行榜类型 */
const userRankTypeArb = fc.constantFrom('invite', 'loss', 'dada', 'diamond', 'uu')

// ==================== 请求参数生成器 ====================

/** 生成优惠券列表请求参数 */
const couponListRequestArb = fc.record({
  page: validPageArb,
  pageSize: validPageSizeArb,
  keyword: optionalKeywordArb,
  type: optionalCouponTypeArb
})

/** 生成优惠券领取记录列表请求参数 */
const couponReceiveListRequestArb = fc.record({
  page: validPageArb,
  pageSize: validPageSizeArb,
  userId: optionalUserIdArb,
  title: optionalTitleArb,
  status: optionalCouponStatusArb
})

/** 生成广告列表请求参数 */
const advertListRequestArb = fc.record({
  page: validPageArb,
  pageSize: validPageSizeArb,
  typeId: optionalAdvertTypeIdArb
})

/** 生成排行榜中奖记录列表请求参数 */
const rankLogListRequestArb = fc.record({
  page: validPageArb,
  pageSize: validPageSizeArb,
  userId: optionalUserIdArb,
  mobile: optionalMobileArb
})

/** 生成用户排行榜请求参数 */
const userRankListRequestArb = fc.record({
  page: validPageArb,
  pageSize: validPageSizeArb,
  type: userRankTypeArb
})

// ==================== 属性测试 ====================

describe('营销活动管理模块属性测试', () => {
  /**
   * Property 1: 搜索参数正确传递
   * 
   * *For any* 搜索条件对象，当用户提交搜索时，API调用应该正确传递所有非空的搜索参数到后端。
   * 
   * **Validates: Requirements 1.2, 1.3, 4.2, 4.3, 4.4, 5.2, 10.2, 10.3, 12.2, 12.3, 13.2**
   * 
   * Feature: marketing-management-frontend, Property 1: 搜索参数正确传递
   */
  describe('Property 1: 搜索参数正确传递', () => {
    it('对于任意优惠券列表搜索参数，buildSearchParams应该正确过滤空值', () => {
      fc.assert(
        fc.property(couponListRequestArb, (params) => {
          const builtParams = buildSearchParams(params)
          
          // 验证：所有非空参数都应该被保留
          for (const [key, value] of Object.entries(params)) {
            if (!isEmptyValue(value)) {
              expect(builtParams[key]).toBe(value)
            } else {
              expect(builtParams[key]).toBeUndefined()
            }
          }
          
          // 验证：构建的参数中不应该有空值
          for (const value of Object.values(builtParams)) {
            expect(isEmptyValue(value)).toBe(false)
          }
        }),
        { numRuns: 100 }
      )
    })

    it('对于任意优惠券领取记录搜索参数，buildSearchParams应该正确过滤空值', () => {
      fc.assert(
        fc.property(couponReceiveListRequestArb, (params) => {
          const builtParams = buildSearchParams(params)
          
          // 验证：所有非空参数都应该被保留
          for (const [key, value] of Object.entries(params)) {
            if (!isEmptyValue(value)) {
              expect(builtParams[key]).toBe(value)
            } else {
              expect(builtParams[key]).toBeUndefined()
            }
          }
          
          // 验证：构建的参数中不应该有空值
          for (const value of Object.values(builtParams)) {
            expect(isEmptyValue(value)).toBe(false)
          }
        }),
        { numRuns: 100 }
      )
    })

    it('对于任意广告列表搜索参数，buildSearchParams应该正确过滤空值', () => {
      fc.assert(
        fc.property(advertListRequestArb, (params) => {
          const builtParams = buildSearchParams(params)
          
          // 验证：所有非空参数都应该被保留
          for (const [key, value] of Object.entries(params)) {
            if (!isEmptyValue(value)) {
              expect(builtParams[key]).toBe(value)
            } else {
              expect(builtParams[key]).toBeUndefined()
            }
          }
          
          // 验证：构建的参数中不应该有空值
          for (const value of Object.values(builtParams)) {
            expect(isEmptyValue(value)).toBe(false)
          }
        }),
        { numRuns: 100 }
      )
    })

    it('对于任意排行榜中奖记录搜索参数，buildSearchParams应该正确过滤空值', () => {
      fc.assert(
        fc.property(rankLogListRequestArb, (params) => {
          const builtParams = buildSearchParams(params)
          
          // 验证：所有非空参数都应该被保留
          for (const [key, value] of Object.entries(params)) {
            if (!isEmptyValue(value)) {
              expect(builtParams[key]).toBe(value)
            } else {
              expect(builtParams[key]).toBeUndefined()
            }
          }
          
          // 验证：构建的参数中不应该有空值
          for (const value of Object.values(builtParams)) {
            expect(isEmptyValue(value)).toBe(false)
          }
        }),
        { numRuns: 100 }
      )
    })

    it('对于任意用户排行榜搜索参数，buildSearchParams应该正确过滤空值', () => {
      fc.assert(
        fc.property(userRankListRequestArb, (params) => {
          const builtParams = buildSearchParams(params)
          
          // 验证：所有非空参数都应该被保留
          for (const [key, value] of Object.entries(params)) {
            if (!isEmptyValue(value)) {
              expect(builtParams[key]).toBe(value)
            } else {
              expect(builtParams[key]).toBeUndefined()
            }
          }
          
          // 验证：构建的参数中不应该有空值
          for (const value of Object.values(builtParams)) {
            expect(isEmptyValue(value)).toBe(false)
          }
        }),
        { numRuns: 100 }
      )
    })
  })


  /**
   * Property 2: 分页参数正确传递
   * 
   * *For any* 页码和页大小组合，当用户切换分页时，API调用应该正确传递page和pageSize参数，
   * 且page >= 1，pageSize > 0。
   * 
   * **Validates: Requirements 1.4, 4.5, 5.5, 10.4, 12.4, 13.6**
   * 
   * Feature: marketing-management-frontend, Property 2: 分页参数正确传递
   */
  describe('Property 2: 分页参数正确传递', () => {
    it('对于任意有效的分页参数，isValidPagination应该返回true', () => {
      fc.assert(
        fc.property(validPageArb, validPageSizeArb, (page, pageSize) => {
          expect(isValidPagination(page, pageSize)).toBe(true)
        }),
        { numRuns: 100 }
      )
    })

    it('对于任意无效的页码，isValidPagination应该返回false', () => {
      fc.assert(
        fc.property(invalidPageArb, validPageSizeArb, (page, pageSize) => {
          expect(isValidPagination(page, pageSize)).toBe(false)
        }),
        { numRuns: 100 }
      )
    })

    it('对于任意无效的页大小，isValidPagination应该返回false', () => {
      fc.assert(
        fc.property(validPageArb, invalidPageSizeArb, (page, pageSize) => {
          expect(isValidPagination(page, pageSize)).toBe(false)
        }),
        { numRuns: 100 }
      )
    })

    it('分页参数应该满足page >= 1且pageSize > 0的约束', () => {
      fc.assert(
        fc.property(
          fc.integer({ min: -100, max: 1000 }),
          fc.integer({ min: -100, max: 100 }),
          (page, pageSize) => {
            const isValid = isValidPagination(page, pageSize)
            const shouldBeValid = page >= 1 && pageSize > 0 && Number.isInteger(page) && Number.isInteger(pageSize)
            expect(isValid).toBe(shouldBeValid)
          }
        ),
        { numRuns: 100 }
      )
    })
  })

  /**
   * Property 3: 表单必填字段验证
   * 
   * *For any* 表单输入，当必填字段为空或格式错误时，表单验证应该失败并阻止提交。
   * 
   * **Validates: Requirements 2.4, 2.5, 6.7, 8.3, 9.4**
   * 
   * Feature: marketing-management-frontend, Property 3: 表单必填字段验证
   */
  describe('Property 3: 表单必填字段验证', () => {
    // 优惠券表单验证
    describe('优惠券表单验证', () => {
      it('对于任意有效的优惠券表单数据，isValidCouponForm应该返回true', () => {
        fc.assert(
          fc.property(validCouponTitleArb, validPriceArb, validDiscountPriceArb, validDaysArb, 
            (title, minPrice, discountPrice, validDays) => {
              expect(isValidCouponForm(title, minPrice, discountPrice, validDays)).toBe(true)
            }
          ),
          { numRuns: 100 }
        )
      })

      it('当优惠券标题为空或纯空白时，isValidCouponForm应该返回false', () => {
        fc.assert(
          fc.property(emptyOrWhitespaceArb, validPriceArb, validDiscountPriceArb, validDaysArb,
            (title, minPrice, discountPrice, validDays) => {
              expect(isValidCouponForm(title, minPrice, discountPrice, validDays)).toBe(false)
            }
          ),
          { numRuns: 100 }
        )
      })

      it('当优惠金额小于等于0时，isValidCouponForm应该返回false', () => {
        fc.assert(
          fc.property(
            validCouponTitleArb, 
            validPriceArb, 
            fc.float({ min: Math.fround(-100), max: Math.fround(0), noNaN: true }),
            validDaysArb,
            (title, minPrice, discountPrice, validDays) => {
              expect(isValidCouponForm(title, minPrice, discountPrice, validDays)).toBe(false)
            }
          ),
          { numRuns: 100 }
        )
      })

      it('当有效期小于等于0或非整数时，isValidCouponForm应该返回false', () => {
        fc.assert(
          fc.property(
            validCouponTitleArb, 
            validPriceArb, 
            validDiscountPriceArb,
            fc.oneof(
              fc.integer({ min: -100, max: 0 }),
              fc.double({ min: Math.fround(0.1), max: Math.fround(10), noNaN: true }).filter(n => !Number.isInteger(n))
            ),
            (title, minPrice, discountPrice, validDays) => {
              expect(isValidCouponForm(title, minPrice, discountPrice, validDays)).toBe(false)
            }
          ),
          { numRuns: 100 }
        )
      })
    })

    // 广告表单验证
    describe('广告表单验证', () => {
      it('对于任意有效的广告表单数据，isValidAdvertForm应该返回true', () => {
        fc.assert(
          fc.property(validImageUrlArb, validTypeIdArb, (imageUrl, typeId) => {
            expect(isValidAdvertForm(imageUrl, typeId)).toBe(true)
          }),
          { numRuns: 100 }
        )
      })

      it('当图片URL为空或纯空白时，isValidAdvertForm应该返回false', () => {
        fc.assert(
          fc.property(emptyOrWhitespaceArb, validTypeIdArb, (imageUrl, typeId) => {
            expect(isValidAdvertForm(imageUrl, typeId)).toBe(false)
          }),
          { numRuns: 100 }
        )
      })

      it('当广告类型ID小于等于0时，isValidAdvertForm应该返回false', () => {
        fc.assert(
          fc.property(validImageUrlArb, fc.integer({ min: -100, max: 0 }), (imageUrl, typeId) => {
            expect(isValidAdvertForm(imageUrl, typeId)).toBe(false)
          }),
          { numRuns: 100 }
        )
      })
    })

    // 广告类型表单验证
    describe('广告类型表单验证', () => {
      it('对于任意有效的广告类型名称，isValidAdvertTypeForm应该返回true', () => {
        fc.assert(
          fc.property(validTypeNameArb, (name) => {
            expect(isValidAdvertTypeForm(name)).toBe(true)
          }),
          { numRuns: 100 }
        )
      })

      it('当广告类型名称为空或纯空白时，isValidAdvertTypeForm应该返回false', () => {
        fc.assert(
          fc.property(emptyOrWhitespaceArb, (name) => {
            expect(isValidAdvertTypeForm(name)).toBe(false)
          }),
          { numRuns: 100 }
        )
      })
    })

    // 排行榜奖品表单验证
    describe('排行榜奖品表单验证', () => {
      it('对于任意有效的排行榜奖品表单数据，isValidRankPrizeForm应该返回true', () => {
        fc.assert(
          fc.property(validRankArb, validCouponTitleArb, validImageUrlArb, validPriceArb,
            (rank, title, imgUrl, price) => {
              expect(isValidRankPrizeForm(rank, title, imgUrl, price)).toBe(true)
            }
          ),
          { numRuns: 100 }
        )
      })

      it('当排名小于等于0或非整数时，isValidRankPrizeForm应该返回false', () => {
        fc.assert(
          fc.property(
            fc.oneof(
              fc.integer({ min: -100, max: 0 }),
              fc.double({ min: Math.fround(0.1), max: Math.fround(10), noNaN: true }).filter(n => !Number.isInteger(n))
            ),
            validCouponTitleArb, 
            validImageUrlArb, 
            validPriceArb,
            (rank, title, imgUrl, price) => {
              expect(isValidRankPrizeForm(rank, title, imgUrl, price)).toBe(false)
            }
          ),
          { numRuns: 100 }
        )
      })

      it('当奖品名称为空或纯空白时，isValidRankPrizeForm应该返回false', () => {
        fc.assert(
          fc.property(validRankArb, emptyOrWhitespaceArb, validImageUrlArb, validPriceArb,
            (rank, title, imgUrl, price) => {
              expect(isValidRankPrizeForm(rank, title, imgUrl, price)).toBe(false)
            }
          ),
          { numRuns: 100 }
        )
      })

      it('当奖品图片URL为空或纯空白时，isValidRankPrizeForm应该返回false', () => {
        fc.assert(
          fc.property(validRankArb, validCouponTitleArb, emptyOrWhitespaceArb, validPriceArb,
            (rank, title, imgUrl, price) => {
              expect(isValidRankPrizeForm(rank, title, imgUrl, price)).toBe(false)
            }
          ),
          { numRuns: 100 }
        )
      })
    })
  })


  /**
   * Property 4: 条件显示字段正确切换
   * 
   * *For any* 广告表单，当跳转类型改变时，应该正确显示/隐藏对应的输入字段（优惠券ID/盒子ID/自定义URL）。
   * 
   * **Validates: Requirements 6.4, 6.5, 6.6**
   * 
   * Feature: marketing-management-frontend, Property 4: 条件显示字段正确切换
   */
  describe('Property 4: 条件显示字段正确切换', () => {
    it('当跳转类型为"不跳转"时，所有条件字段都应该隐藏', () => {
      const result = getVisibleFieldsByJumpType(AdvertJumpType.None)
      expect(result.showCouponId).toBe(false)
      expect(result.showGoodsId).toBe(false)
      expect(result.showUrlLink).toBe(false)
    })

    it('当跳转类型为"优惠券"时，只显示优惠券ID字段', () => {
      const result = getVisibleFieldsByJumpType(AdvertJumpType.Coupon)
      expect(result.showCouponId).toBe(true)
      expect(result.showGoodsId).toBe(false)
      expect(result.showUrlLink).toBe(false)
    })

    it('当跳转类型为"一番赏"时，只显示盒子ID字段', () => {
      const result = getVisibleFieldsByJumpType(AdvertJumpType.YiFanShang)
      expect(result.showCouponId).toBe(false)
      expect(result.showGoodsId).toBe(true)
      expect(result.showUrlLink).toBe(false)
    })

    it('当跳转类型为"无限赏"时，只显示盒子ID字段', () => {
      const result = getVisibleFieldsByJumpType(AdvertJumpType.WuXianShang)
      expect(result.showCouponId).toBe(false)
      expect(result.showGoodsId).toBe(true)
      expect(result.showUrlLink).toBe(false)
    })

    it('当跳转类型为"连击赏"时，只显示盒子ID字段', () => {
      const result = getVisibleFieldsByJumpType(AdvertJumpType.LianJiShang)
      expect(result.showCouponId).toBe(false)
      expect(result.showGoodsId).toBe(true)
      expect(result.showUrlLink).toBe(false)
    })

    it('当跳转类型为"自定义URL"时，只显示跳转链接字段', () => {
      const result = getVisibleFieldsByJumpType(AdvertJumpType.CustomUrl)
      expect(result.showCouponId).toBe(false)
      expect(result.showGoodsId).toBe(false)
      expect(result.showUrlLink).toBe(true)
    })

    it('对于任意跳转类型，最多只有一个条件字段显示', () => {
      fc.assert(
        fc.property(jumpTypeArb, (jumpType) => {
          const result = getVisibleFieldsByJumpType(jumpType)
          const visibleCount = [result.showCouponId, result.showGoodsId, result.showUrlLink]
            .filter(Boolean).length
          expect(visibleCount).toBeLessThanOrEqual(1)
        }),
        { numRuns: 100 }
      )
    })

    it('对于任意跳转类型，条件字段显示逻辑应该一致', () => {
      fc.assert(
        fc.property(jumpTypeArb, (jumpType) => {
          const result = getVisibleFieldsByJumpType(jumpType)
          
          // 验证逻辑一致性
          if (jumpType === AdvertJumpType.None) {
            expect(result.showCouponId).toBe(false)
            expect(result.showGoodsId).toBe(false)
            expect(result.showUrlLink).toBe(false)
          } else if (jumpType === AdvertJumpType.Coupon) {
            expect(result.showCouponId).toBe(true)
            expect(result.showGoodsId).toBe(false)
            expect(result.showUrlLink).toBe(false)
          } else if ([AdvertJumpType.YiFanShang, AdvertJumpType.WuXianShang, AdvertJumpType.LianJiShang].includes(jumpType)) {
            expect(result.showCouponId).toBe(false)
            expect(result.showGoodsId).toBe(true)
            expect(result.showUrlLink).toBe(false)
          } else if (jumpType === AdvertJumpType.CustomUrl) {
            expect(result.showCouponId).toBe(false)
            expect(result.showGoodsId).toBe(false)
            expect(result.showUrlLink).toBe(true)
          }
        }),
        { numRuns: 100 }
      )
    })
  })

  /**
   * Property 5: API响应格式一致性
   * 
   * *For any* API调用，成功时应返回 `{ code: 0, message: "success", data: {...} }` 格式，
   * 失败时应返回 `{ code: number, message: "error message" }` 格式。
   * 
   * **Validates: Requirements 15.25, 15.26**
   * 
   * Feature: marketing-management-frontend, Property 5: API响应格式一致性
   */
  describe('Property 5: API响应格式一致性', () => {
    /** 生成有效的成功响应 */
    const validSuccessResponseArb = fc.record({
      code: fc.constant(0),
      message: fc.string(),
      data: fc.anything()
    })

    /** 生成有效的错误响应 */
    const validErrorResponseArb = fc.record({
      code: fc.integer({ min: 1, max: 9999 }), // 非0的错误码
      message: fc.string({ minLength: 1 })
    })

    /** 生成无效的响应（缺少字段或格式错误） */
    const invalidResponseArb = fc.oneof(
      fc.constant(null),
      fc.constant(undefined),
      fc.constant({}),
      fc.record({ code: fc.string() as any, message: fc.string() }), // code类型错误
      fc.record({ code: fc.integer(), message: fc.integer() as any }) // message类型错误
    )

    it('对于任意有效的成功响应，isValidSuccessResponse应该返回true', () => {
      fc.assert(
        fc.property(validSuccessResponseArb, (response) => {
          expect(isValidSuccessResponse(response)).toBe(true)
        }),
        { numRuns: 100 }
      )
    })

    it('对于任意有效的错误响应，isValidErrorResponse应该返回true', () => {
      fc.assert(
        fc.property(validErrorResponseArb, (response) => {
          expect(isValidErrorResponse(response)).toBe(true)
        }),
        { numRuns: 100 }
      )
    })

    it('对于任意无效的响应，isValidApiResponse应该返回false', () => {
      fc.assert(
        fc.property(invalidResponseArb, (response) => {
          expect(isValidApiResponse(response)).toBe(false)
        }),
        { numRuns: 100 }
      )
    })

    it('成功响应的code必须为0', () => {
      fc.assert(
        fc.property(
          fc.integer(),
          fc.string(),
          fc.anything(),
          (code, message, data) => {
            const response = { code, message, data }
            const isSuccess = isValidSuccessResponse(response)
            expect(isSuccess).toBe(code === 0)
          }
        ),
        { numRuns: 100 }
      )
    })

    it('错误响应的code必须非0且message非空', () => {
      fc.assert(
        fc.property(
          fc.integer(),
          fc.string(),
          (code, message) => {
            const response = { code, message }
            const isError = isValidErrorResponse(response)
            const shouldBeError = code !== 0 && message.length > 0
            expect(isError).toBe(shouldBeError)
          }
        ),
        { numRuns: 100 }
      )
    })

    it('缺少必需字段的响应应该验证失败', () => {
      // 测试缺少code字段
      expect(isValidApiResponse({ message: 'test', data: null })).toBe(false)
      // 测试缺少message字段
      expect(isValidApiResponse({ code: 0, data: null })).toBe(false)
      // 测试null响应
      expect(isValidApiResponse(null)).toBe(false)
      // 测试undefined响应
      expect(isValidApiResponse(undefined)).toBe(false)
    })
  })
})
