import { getInventoryItemById } from '../../repositories/inventory-repo.js'
import { getOrderById } from '../../repositories/order-repo.js'
import { getTaskById } from '../../repositories/task-repo.js'
import { createHttpError } from '../../utils/http.js'
import { mapAdminTaskSummary } from './admin-task-read-helpers.js'

import type { AdminInventoryItemListItem } from '../../types/admin-read-models.js'
import type { InventoryItemRow } from '../../types/repository-rows.js'

export async function mapAdminInventoryListItem(item: InventoryItemRow): Promise<AdminInventoryItemListItem> {
  const task = item.reserved_by_task_id ? await getTaskById(item.reserved_by_task_id) : null
  const order = task?.order_id ? await getOrderById(task.order_id) : null
  const taskSummary = task ? mapAdminTaskSummary(task) : null

  return {
    inventoryItemId: item.id,
    skuCode: item.sku_code,
    batchNo: item.batch_no,
    credentialType: item.credential_type || 'tencent_code',
    inventoryGroupCode: String(item.inventory_group_code || '').trim(),
    displayValue: item.display_value,
    status: item.status,
    reservedByTaskId: item.reserved_by_task_id,
    reservedByTaskNo: task?.task_no || '',
    platformOrderId: order?.platform_order_id || '',
    systemBindingStatus: item.status === 'consumed' ? 'system_bound' : (taskSummary?.systemBindingStatus || 'pending_binding'),
    userBindingStatus: item.status === 'consumed' ? 'binding_completed' : (taskSummary?.userBindingStatus || 'not_started'),
    invalidReason: item.invalid_reason || '',
    deliveredAt: item.delivered_at,
    createdAt: item.created_at,
    updatedAt: item.updated_at,
  }
}

export async function getRequiredInventoryItem(inventoryItemId: number | string): Promise<InventoryItemRow> {
  const inventoryItem = await getInventoryItemById(Number(inventoryItemId))

  if (!inventoryItem) {
    throw createHttpError('库存项不存在', {
      statusCode: 404,
      errorCode: 'admin_inventory_not_found',
    })
  }

  return inventoryItem
}
