import fs from 'node:fs/promises'

const runtimePath = new URL('../pocket-base/bai_api_pb_hooks/bai_api_shared/config/runtime.js', import.meta.url)
const runtimeText = await fs.readFile(runtimePath, 'utf8')

function readRuntimeValue(name) {
  const match = runtimeText.match(new RegExp(`${name}:\\s*'([^']*)'`))
  if (!match) {
    throw new Error(`未在 runtime.js 中找到 ${name}`)
  }
  return match[1]
}

const baseUrl = readRuntimeValue('APP_BASE_URL')
const adminToken = readRuntimeValue('POCKETBASE_AUTH_TOKEN')

function assert(condition, message) {
  if (!condition) {
    throw new Error(message)
  }
}

async function requestJson(path, options = {}) {
  const res = await fetch(`${baseUrl}${path}`, options)
  const text = await res.text()
  let json = null

  try {
    json = text ? JSON.parse(text) : null
  } catch {
    throw new Error(`接口 ${path} 返回了非 JSON 响应：${text}`)
  }

  return { res, json }
}

async function main() {
  const knownCompanyId = 'WX-COMPANY-10001'
  const initialOwnerOpenid = 'wx-owner-create'
  const updatedOwnerOpenid = 'wx-owner-updated'

  const createResult = await requestJson('/pb/api/collections/tbl_company/records', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      company_name: '原生接口测试公司',
      company_nationality: '中国',
      company_nationality_code: 'CN',
      company_province: '上海',
      company_province_code: '310000',
      company_city: '上海',
      company_city_code: '310100',
      company_district: '浦东新区',
      company_district_code: '310115',
      company_status: '有效',
      company_owner_openid: initialOwnerOpenid,
    }),
  })

  assert(createResult.res.ok, `公开创建失败：${JSON.stringify(createResult.json)}`)
  assert(typeof createResult.json?.company_id === 'string' && createResult.json.company_id.startsWith('WX-COMPANY-'), '公开创建未自动生成 company_id')
  assert(createResult.json?.company_owner_openid === initialOwnerOpenid, '公开创建返回的 company_owner_openid 不匹配')
  assert(createResult.json?.company_city_code === '310100', '公开创建返回的 company_city_code 不匹配')

  const byCompanyIdResult = await requestJson(
    `/pb/api/collections/tbl_company/records?filter=${encodeURIComponent(`company_id="${knownCompanyId}"`)}&perPage=1&page=1`
  )

  assert(byCompanyIdResult.res.ok, `按 company_id 查询失败：${JSON.stringify(byCompanyIdResult.json)}`)
  assert(byCompanyIdResult.json?.totalItems === 1, `按 company_id 查询结果数量不为 1：${JSON.stringify(byCompanyIdResult.json)}`)
  assert(byCompanyIdResult.json?.items?.[0]?.company_id === knownCompanyId, '按 company_id 查询返回了错误的记录')

  const listResult = await requestJson('/pb/api/collections/tbl_company/records?perPage=5&page=1')
  assert(listResult.res.ok, `公开列表查询失败：${JSON.stringify(listResult.json)}`)
  assert((listResult.json?.totalItems || 0) >= 1, '公开列表查询未返回任何数据')

  const createdCompanyId = createResult.json.company_id
  const createdLookupResult = await requestJson(
    `/pb/api/collections/tbl_company/records?filter=${encodeURIComponent(`company_id="${createdCompanyId}"`)}&perPage=1&page=1`
  )
  assert(createdLookupResult.res.ok, `按 company_id 查询测试记录失败：${JSON.stringify(createdLookupResult.json)}`)
  assert(createdLookupResult.json?.totalItems === 1, `按 company_id 查询测试记录数量不为 1：${JSON.stringify(createdLookupResult.json)}`)

  const createdRecordId = createdLookupResult.json.items[0].id
  const updateResult = await requestJson(`/pb/api/collections/tbl_company/records/${createdRecordId}`, {
    method: 'PATCH',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${adminToken}`,
    },
    body: JSON.stringify({
      company_name: '原生接口测试公司-已更新',
      company_owner_openid: updatedOwnerOpenid,
      company_district: '徐汇区',
      company_district_code: '310104',
    }),
  })
  assert(updateResult.res.ok, `按 company_id 定位后更新失败：${JSON.stringify(updateResult.json)}`)
  assert(updateResult.json?.company_name === '原生接口测试公司-已更新', '更新后的 company_name 不正确')
  assert(updateResult.json?.company_owner_openid === updatedOwnerOpenid, '更新后的 company_owner_openid 不正确')
  assert(updateResult.json?.company_district_code === '310104', '更新后的 company_district_code 不正确')

  const cleanupResult = await requestJson(`/pb/api/collections/tbl_company/records/${createResult.json.id}`, {
    method: 'DELETE',
    headers: {
      Authorization: `Bearer ${adminToken}`,
    },
  })

  assert(cleanupResult.res.ok, `测试清理失败：${JSON.stringify(cleanupResult.json)}`)

  console.log(JSON.stringify({
    createdCompanyId: createdCompanyId,
    queriedCompanyId: byCompanyIdResult.json.items[0].company_id,
    publicListTotalItems: listResult.json.totalItems,
    updatedRecordId: createdRecordId,
    updatedOwnerOpenid: updateResult.json.company_owner_openid,
    updatedDistrictCode: updateResult.json.company_district_code,
    cleanupDeletedId: createResult.json.id,
  }, null, 2))
}

await main()
