import type { JsonObject } from '../../types/json.js'
import {
  listFulfillmentProfileRequirements,
  replaceFulfillmentProfileRequirements,
  upsertFulfillmentProfile,
  type FulfillmentProfileRequirementInput,
} from '../../repositories/fulfillment-profile-repo.js'
import { nowIso } from '../../utils/time.js'

type CoreProfile = {
  profileKey: string
  name: string
  executorKey: string
  requiresClaim: boolean
  autoDispatch: boolean
  inventoryStrategy: string
  requirements: FulfillmentProfileRequirementInput[]
}

const CORE_PROFILES: CoreProfile[] = [
  {
    profileKey: 'manual_review',
    name: '人工发货',
    executorKey: 'manual_dispatch',
    requiresClaim: false,
    autoDispatch: false,
    inventoryStrategy: 'static_pool',
    requirements: [],
  },
  {
    profileKey: 'kuaishou_ct_assisted',
    name: 'kuaishou-lewan 履约',
    executorKey: 'kuaishou_ct_assisted',
    requiresClaim: false,
    autoDispatch: false,
    inventoryStrategy: 'external_platform',
    requirements: [],
  },
  {
    profileKey: 'kuaishou_feifei',
    name: 'kuaishou-feifei 履约',
    executorKey: 'kuaishou_feifei',
    requiresClaim: true,
    autoDispatch: false,
    inventoryStrategy: 'external_platform',
    requirements: [],
  },
  {
    profileKey: 'affiliate_dash',
    name: 'affiliate-dash 履约',
    executorKey: 'affiliate_dash',
    requiresClaim: true,
    autoDispatch: false,
    inventoryStrategy: 'external_platform',
    requirements: [],
  },
]

export async function ensureFulfillmentCatalogBootstrapped() {
  await ensureCoreProfiles()
}

async function ensureCoreProfiles() {
  const timestamp = nowIso()
  const profileMap: JsonObject = {}

  for (const profile of CORE_PROFILES) {
    const saved = await upsertFulfillmentProfile({
      profileKey: profile.profileKey,
      name: profile.name,
      executorKey: profile.executorKey,
      requiresClaim: profile.requiresClaim,
      autoDispatch: profile.autoDispatch,
      inventoryStrategy: profile.inventoryStrategy,
      configJson: '{}',
      createdAt: timestamp,
      updatedAt: timestamp,
    })

    if (!saved) {
      continue
    }

    profileMap[profile.profileKey] = saved
    const currentRequirements = await listFulfillmentProfileRequirements(saved.id)
    if (currentRequirements.length !== profile.requirements.length) {
      await replaceFulfillmentProfileRequirements(saved.id, profile.requirements, timestamp)
    }
  }

  return profileMap
}
