import request from '@/utils/http'

/**
 * 租户套餐管理 API
 */

/**
 * 获取租户套餐分页列表
 */
export function fetchTenantPackageList(params?: Api.Tenant.TenantPackageQueryParams) {
  return request.get<Api.Tenant.TenantPackageListResponse>({
    url: '/api/admin/v1/tenant-packages',
    params
  })
}

/**
 * 公共租户套餐列表（匿名可访问）
 */
export function fetchPublicTenantPackageList(params?: Api.Tenant.TenantPackageQueryParams) {
  return request.get<Api.Tenant.PublicTenantPackageListResponse>({
    url: '/api/public/v1/tenant-packages',
    params
  })
}

/**
 * 获取租户套餐详情
 */
export function fetchTenantPackageDetail(tenantPackageId: string) {
  return request.get<Api.Tenant.TenantPackageDto>({
    url: `/api/admin/v1/tenant-packages/${tenantPackageId}`
  })
}

/**
 * 创建租户套餐
 */
export function fetchCreateTenantPackage(data: Api.Tenant.CreateTenantPackageCommand) {
  return request.post<Api.Tenant.TenantPackageDto>({
    url: '/api/admin/v1/tenant-packages',
    data
  })
}

/**
 * 更新租户套餐
 */
export function fetchUpdateTenantPackage(
  tenantPackageId: string,
  data: Api.Tenant.UpdateTenantPackageCommand
) {
  return request.put<Api.Tenant.TenantPackageDto>({
    url: `/api/admin/v1/tenant-packages/${tenantPackageId}`,
    data: {
      ...data,
      tenantPackageId
    }
  })
}

/**
 * 删除租户套餐（软删）
 */
export function fetchDeleteTenantPackage(tenantPackageId: string) {
  return request.del<boolean>({
    url: `/api/admin/v1/tenant-packages/${tenantPackageId}`
  })
}

/**
 * 查询套餐使用统计（订阅关联数量、使用租户数量）
 */
export function fetchTenantPackageUsages(tenantPackageIds?: string[]) {
  const params = new URLSearchParams()
  if (tenantPackageIds?.length) {
    tenantPackageIds.forEach((id) => params.append('tenantPackageIds', id))
  }

  return request.get<Api.Tenant.TenantPackageUsageDto[]>({
    url: '/api/admin/v1/tenant-packages/usages',
    params,
    showErrorMessage: false
  })
}

/**
 * 查询套餐当前使用租户列表（按有效订阅口径）
 */
export function fetchTenantPackageTenants(
  tenantPackageId: string,
  params: { keyword?: string; page?: number; pageSize?: number; expiringWithinDays?: number } = {}
) {
  return request.get<Api.Common.PageResult<Api.Tenant.TenantPackageTenantDto>>({
    url: `/api/admin/v1/tenant-packages/${tenantPackageId}/tenants`,
    params: {
      keyword: params.keyword || undefined,
      expiringWithinDays: params.expiringWithinDays ?? undefined,
      page: params.page ?? 1,
      pageSize: params.pageSize ?? 20
    }
  })
}
