import { createTaskEvent } from '../../../repositories/task-event-repo.js'
import { updateTask } from '../../../repositories/task-repo.js'
import { TASK_STATUS } from '../../../domain/task-status.js'
import { asJsonObject, type JsonObject } from '../../../types/json.js'
import type { TaskRow } from '../../../types/repository/rows.js'
import { addHours } from '../../../utils/time.js'
import { normalizeKuaishouCloudFlow } from './domain.js'
import { parseTaskContext } from './task-context.js'

export function isKuaishouCloudMockTask(task: Partial<TaskRow> | null | undefined) {
  return isKuaishouCloudMockContext(parseTaskContext(task))
}

export function isKuaishouCloudMockContext(context: JsonObject = {}) {
  const flow = asJsonObject(context.kuaishouCloudFulfillment)
  const mock = flow.mock && typeof flow.mock === 'object' ? flow.mock : context.mock

  return Boolean(mock && typeof mock === 'object' && (mock as JsonObject).enabled === true)
}

export function buildMockVerifiedKuaishouCloudFlow(value: unknown, timestamp: string) {
  const flow = normalizeKuaishouCloudFlow(value)
  const source = flow as JsonObject
  const bindUrl =
    flow.binding.bindUrl ||
    `https://example.com/mock-kuaishou-cloud-bind?task=mock&ts=${encodeURIComponent(timestamp)}`
  const vnPhone = flow.binding.vnPhone || '13800000000'
  const roleName = flow.binding.roleName || flow.role.name || '测试角色'
  const roleId = flow.binding.roleId || flow.role.rid || '10001'

  return {
    ...flow,
    mock: {
      ...asJsonObject(source.mock),
      enabled: true,
    },
    binding: {
      ...flow.binding,
      prepareStatus: 'ready',
      vnId: flow.binding.vnId || 900001,
      vnPhone,
      bindUrl,
      bindPreparedAt: flow.binding.bindPreparedAt || timestamp,
      bindExpiresAt: flow.binding.bindExpiresAt || addHours(timestamp, 24),
      roleName,
      roleId,
    },
    role: {
      ...flow.role,
      status: 'ready',
      name: roleName,
      rid: roleId,
      refreshedAt: flow.role.refreshedAt || timestamp,
      errorMessage: '',
      rawInfo: flow.role.rawInfo || {
        mock: true,
      },
    },
  }
}

/** 开发 mock：跳过真实 CT，直接落成 completed */
export async function completeMockKuaishouCloudTask(task: TaskRow, timestamp: string) {
  const taskContext = parseTaskContext(task)
  const flow = normalizeKuaishouCloudFlow(taskContext.kuaishouCloudFulfillment)
  const source = flow as JsonObject
  const nextFlow = {
    ...flow,
    mock: {
      ...asJsonObject(source.mock),
      enabled: true,
    },
    dispatch: {
      ...flow.dispatch,
      status: 'success',
      dispatchAt: timestamp,
      dispatchBy: {
        source: 'claim_page_mock',
      },
      note: '开发 mock 已模拟发货成功',
      items: flow.deliveryItems,
    },
    returnNumber: {
      ...flow.returnNumber,
      status: 'success',
      returnedAt: timestamp,
      returnedBy: {
        source: 'claim_page_mock',
      },
    },
    consume: {
      ...flow.consume,
      status: 'success',
      consumedAt: timestamp,
      errorMessage: '',
    },
  }

  await updateTask(task.id, {
    task_status: TASK_STATUS.COMPLETED,
    delivery_status: 'success',
    result_code: 'mock_success',
    result_message: '开发 mock 已模拟兑换成功',
    user_action_status: 'not_required',
    last_error: '',
    context_json: JSON.stringify({
      ...taskContext,
      kuaishouCloudFulfillment: nextFlow,
    }),
    redeemed_at: timestamp,
    updated_at: timestamp,
  })

  await createTaskEvent(
    task.id,
    'kuaishou_cloud_mock_redeemed',
    {
      source: 'claim_page_mock',
      deliveryItems: flow.deliveryItems,
    },
    timestamp,
  )
}
