import { Router } from 'express'

import { createRateLimitMiddleware, getParamRateLimitKey } from '../middleware/rate-limit.js'
import {
  confirmKuaishouCloudClaimRole,
  getKuaishouCloudClaimDetail,
  rebindKuaishouCloudClaimRole,
  redeemKuaishouCloudClaim,
  submitAffiliateDashClaim,
  submitClaimUid,
} from '../services/claim/kuaishou-cloud-claim-service.js'
import { buildNotFoundPayload, createRouteHandler } from '../utils/http.js'

const router = Router()
const claimReadRateLimit = createRateLimitMiddleware({
  scope: 'claim:read',
  windowMs: 60_000,
  max: 120,
  key: getParamRateLimitKey('token'),
})
const claimWriteRateLimit = createRateLimitMiddleware({
  scope: 'claim:write',
  windowMs: 60_000,
  max: 30,
  key: getParamRateLimitKey('token'),
})
const claimRebindRateLimit = createRateLimitMiddleware({
  scope: 'claim:rebind',
  windowMs: 60_000,
  max: 3,
  key: getParamRateLimitKey('token'),
})

router.get(
  '/:token',
  claimReadRateLimit,
  createRouteHandler((req) => getKuaishouCloudClaimDetail(req.params.token), {
    errorMessage: '查询快手领取详情失败',
    scope: '[claims/:token]',
  }),
)

router.post(
  '/:token/uid',
  claimWriteRateLimit,
  createRouteHandler((req) => submitClaimUid(req.params.token, req.body || {}), {
    successMessage: 'UID 已提交',
    errorMessage: '提交 UID 失败',
    scope: '[claims/:token/uid]',
  }),
)

router.post(
  '/:token/affiliate-dash/submit',
  claimWriteRateLimit,
  createRouteHandler((req) => submitAffiliateDashClaim(req.params.token, req.body || {}), {
    successMessage: '发货已提交',
    errorMessage: '提交发货失败',
    scope: '[claims/:token/affiliate-dash/submit]',
  }),
)

router.post(
  '/:token/kuaishou-cloud/confirm-role',
  claimWriteRateLimit,
  createRouteHandler((req) => confirmKuaishouCloudClaimRole(req.params.token), {
    successMessage: '角色已确认',
    errorMessage: '确认角色失败',
    scope: '[claims/:token/kuaishou-cloud/confirm-role]',
  }),
)

router.post(
  '/:token/kuaishou-cloud/rebind-role',
  claimRebindRateLimit,
  createRouteHandler((req) => rebindKuaishouCloudClaimRole(req.params.token), {
    successMessage: '角色换绑资源已准备完成',
    errorMessage: '换绑角色失败',
    scope: '[claims/:token/kuaishou-cloud/rebind-role]',
  }),
)

router.post(
  '/:token/kuaishou-cloud/redeem',
  claimWriteRateLimit,
  createRouteHandler((req) => redeemKuaishouCloudClaim(req.params.token), {
    successMessage: '兑换请求已提交',
    errorMessage: '兑换失败',
    scope: '[claims/:token/kuaishou-cloud/redeem]',
  }),
)

router.use((req, res) => {
  res.status(404).json(buildNotFoundPayload(req))
})

export default router
