export interface ContractItem {
  id: string
  name: string
  order: number
  createdAt: string
}

export const normalizeOrder = (list: ContractItem[]): ContractItem[] =>
  list.map((item, index) => ({
    ...item,
    order: index,
    createdAt: item.createdAt || new Date().toISOString()
  }))

export const formatDateTime = (value: string) => {
  if (!value) return '-'
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return '-'
  const pad = (n: number) => String(n).padStart(2, '0')
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
}

export const normalizeContractsFromPayload = (value: unknown): ContractItem[] => {
  if (!Array.isArray(value)) return []
  return value
    .filter(item => item && typeof item === 'object')
    .map((item, index) => {
      const row = item as Partial<ContractItem>
      const name = typeof row.name === 'string' ? row.name.trim() : ''
      const createdAt = typeof row.createdAt === 'string' ? row.createdAt : new Date().toISOString()
      const id = typeof row.id === 'string' ? row.id : `import-contract-${index}`
      return {
        id,
        name: name || `导入合同段-${index + 1}`,
        order: index,
        createdAt
      }
    })
}

export const isEntryRelatedToAnyContract = (
  key: string,
  contractIds: Set<string>,
  matcher: (entryKey: string, contractId: string) => boolean
) => {
  for (const contractId of contractIds) {
    if (matcher(key, contractId)) return true
  }
  return false
}
