import { listMessageDeliveries } from '../../repositories/message-delivery-repo.js'
import { normalizeDateQuery, normalizePage, normalizePageSize, safeParseJson } from './admin-query-utils.js'

import type { AdminMessageDeliveryListQueryInput } from '../../types/admin-read-inputs.js'

type JsonObject = Record<string, any>

export async function getAdminMessageDeliveries(query: AdminMessageDeliveryListQueryInput = {}) {
  const page = normalizePage(query.page)
  const pageSize = normalizePageSize(query.pageSize)
  const { items, total } = await listMessageDeliveries({
    page,
    pageSize,
    provider: String(query.provider || '').trim(),
    platform: String(query.platform || '').trim(),
    status: String(query.status || '').trim(),
    shopId: String(query.shopId || '').trim(),
    platformOrderId: String(query.platformOrderId || '').trim(),
    taskNo: String(query.taskNo || '').trim(),
    dateFrom: normalizeDateQuery(query.dateFrom),
    dateTo: normalizeDateQuery(query.dateTo, true),
  })

  return {
    items: items.map(mapAdminMessageDeliveryListItem),
    pagination: { page, pageSize, total },
  }
}

function mapAdminMessageDeliveryListItem(item: JsonObject) {
  return {
    deliveryId: Number(item.id),
    provider: String(item.provider || '').trim(),
    platform: String(item.platform || '').trim(),
    shopId: String(item.shop_id || '').trim(),
    shopName: String(item.shop_name || '').trim(),
    channel: String(item.channel || '').trim(),
    orderId: item.order_id ? Number(item.order_id) : null,
    taskId: item.task_id ? Number(item.task_id) : null,
    taskNo: String(item.task_no || '').trim(),
    taskStatus: String(item.task_status || '').trim(),
    platformOrderId: String(item.platform_order_id || '').trim(),
    recipientKey: String(item.recipient_key || '').trim(),
    messageContent: String(item.message_content || '').trim(),
    claimUrl: String(item.claim_url || '').trim(),
    status: String(item.status || '').trim(),
    requestUrl: String(item.request_url || '').trim(),
    responseStatus: Number(item.response_status || 0),
    response: safeParseJson(item.response_json),
    errorMessage: String(item.error_message || '').trim(),
    sentAt: item.sent_at || null,
    createdAt: item.created_at,
    updatedAt: item.updated_at,
  }
}
