import test from 'node:test'
import assert from 'node:assert/strict'

import { ensureKuaishouIndustryAccessToken, shouldRefreshAccessToken } from './token-service.js'
import type {
  KuaishouIndustryShopConfig,
  KuaishouIndustrySourceConfig,
} from './source-config-service.js'

test('shouldRefreshAccessToken refreshes missing or expiring tokens', () => {
  assert.equal(
    shouldRefreshAccessToken(
      createConfig({
        accessToken: '',
        accessTokenExpiresAt: '',
      }),
    ),
    true,
  )

  assert.equal(
    shouldRefreshAccessToken(
      createConfig({
        accessToken: 'token',
        accessTokenExpiresAt: new Date(Date.now() + 10 * 60 * 1000).toISOString(),
      }),
    ),
    true,
  )

  assert.equal(
    shouldRefreshAccessToken(
      createConfig({
        accessToken: 'token',
        accessTokenExpiresAt: new Date(Date.now() - 10 * 1000).toISOString(),
      }),
    ),
    true,
  )
})

test('shouldRefreshAccessToken keeps valid tokens without a forced refresh', () => {
  assert.equal(
    shouldRefreshAccessToken(
      createConfig({
        accessToken: 'token',
        accessTokenExpiresAt: '',
      }),
    ),
    false,
  )

  assert.equal(
    shouldRefreshAccessToken(
      createConfig({
        accessToken: 'token',
        accessTokenExpiresAt: new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString(),
      }),
    ),
    false,
  )
})

test('ensureKuaishouIndustryAccessToken requires sellerId when multiple shops are enabled', async () => {
  await assert.rejects(
    () =>
      ensureKuaishouIndustryAccessToken({
        config: createConfig({
          shops: [
            createShop({ sellerId: 'seller-a', accessToken: 'token-a' }),
            createShop({ sellerId: 'seller-b', accessToken: 'token-b' }),
          ],
        }),
      }),
    {
      message: '存在多个快手行业电子凭证店铺授权，请指定 sellerId',
      errorCode: 'kuaishou_industry_missing_seller_id',
    },
  )
})

test('ensureKuaishouIndustryAccessToken selects the token by sellerId', async () => {
  const result = await ensureKuaishouIndustryAccessToken({
    sellerId: 'seller-b',
    config: createConfig({
      shops: [
        createShop({ sellerId: 'seller-a', accessToken: 'token-a' }),
        createShop({ sellerId: 'seller-b', accessToken: 'token-b' }),
      ],
    }),
  })

  assert.equal(result.accessToken, 'token-b')
  assert.equal(result.refreshed, false)
  assert.equal(result.shop.sellerId, 'seller-b')
})

function createConfig(
  patch: Partial<KuaishouIndustrySourceConfig> = {},
): KuaishouIndustrySourceConfig {
  return {
    enabled: true,
    baseUrl: 'https://openapi.kwaixiaodian.com',
    authBaseUrl: 'https://open.kwaixiaodian.com',
    redirectUri: '',
    scopes: '',
    authState: '',
    appKey: 'app-key',
    appSecret: 'app-secret',
    signSecret: 'sign-secret',
    messageSecret: 'message-secret',
    accessToken: 'token',
    refreshToken: 'refresh-token',
    accessTokenExpiresAt: new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString(),
    refreshTokenExpiresAt: '',
    openId: '',
    grantedScopes: '',
    sellerId: '',
    provider: 'kuaishou-industry',
    platform: 'kuaishou',
    shopId: 'kuaishou-industry',
    shopName: '快手行业电子凭证',
    version: '1',
    shops: [],
    lastRefreshedAt: '',
    lastRefreshError: '',
    ...patch,
  }
}

function createShop(patch: Partial<KuaishouIndustryShopConfig> = {}): KuaishouIndustryShopConfig {
  return {
    enabled: true,
    sellerId: 'seller-a',
    shopId: 'seller-a',
    shopName: '测试店铺',
    customShopName: '自定义测试店铺',
    authState: '',
    accessToken: 'token',
    refreshToken: 'refresh-token',
    accessTokenExpiresAt: new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString(),
    refreshTokenExpiresAt: '',
    openId: '',
    grantedScopes: '',
    lastRefreshedAt: '',
    lastRefreshError: '',
    ...patch,
  }
}
