import type { JobScheduleData } from '../types/api'
import type { CopyMissionData } from '../types/copyMission'
import type { PlacementTopicData } from '../types/placementTopic'
import { describeCron } from './scheduleCron'
import { jobTemplateLabel } from './jobTemplate'

export const CRON_PRESETS: Array<{ label: string; value: string }> = [
  { label: '每天 09:00', value: '0 9 * * *' },
  { label: '每週一 09:00', value: '0 9 * * 1' },
  { label: '每 6 小時', value: '0 */6 * * *' },
  { label: '每 12 小時', value: '0 */12 * * *' },
]

export const SCHEDULE_TIMEZONE = 'Asia/Taipei'

export type ScheduleKind = 'placement_topic_scan' | 'copy_mission_scan'

export type ScheduleKindMeta = {
  kind: ScheduleKind
  label: string
  description: string
  templateType: 'placement-scan' | 'scan-viral'
  configureHint: string
}

export const SCHEDULE_KINDS: ScheduleKindMeta[] = [
  {
    kind: 'placement_topic_scan',
    label: '找 TA · 定期雙軌海巡',
    description: '依主題研究地圖勾選的節點，定期重跑海巡找貼文；不會自動發文，留言仍須手動 po。',
    templateType: 'placement-scan',
    configureHint: '請先在主題研究地圖勾選節點並儲存，再啟用排程。',
  },
  {
    kind: 'copy_mission_scan',
    label: '拷貝忍者 · 定期爆款海巡',
    description: '依拷貝任務內勾選的標籤，定期重跑爆款海巡；不會自動發文，仍須手動 po。',
    templateType: 'scan-viral',
    configureHint: '請先在拷貝任務勾選搜尋標籤並儲存，再啟用排程。',
  },
]

const KIND_BY_TEMPLATE = new Map(
  SCHEDULE_KINDS.map((item) => [item.templateType, item] as const),
)

export function isManagedScheduleTemplate(templateType: string): boolean {
  return templateType === 'placement-scan' || templateType === 'scan-viral'
}

export function filterManagedSchedules<T extends { template_type: string }>(schedules: T[]): T[] {
  return schedules.filter((item) => isManagedScheduleTemplate(item.template_type))
}

export function scheduleKindMeta(templateType: string): ScheduleKindMeta | null {
  return KIND_BY_TEMPLATE.get(templateType as ScheduleKindMeta['templateType']) ?? null
}

export function cronPresetLabel(cron: string): string {
  return CRON_PRESETS.find((preset) => preset.value === cron)?.label ?? describeCron(cron)
}

type BrandLike = { id: string; display_name?: string; seed_query?: string }

export function resolvePlacementScanTarget(
  schedule: JobScheduleData,
  topics: PlacementTopicData[],
  brands: BrandLike[] = [],
): { label: string; href: string; source: string } {
  const topic = topics.find((item) => item.id === schedule.scope_id)
  if (topic) {
    const name = topic.topic_name?.trim() || topic.seed_query?.trim() || '未命名主題'
    return {
      label: name,
      href: `/placement/topics/${encodeURIComponent(topic.id)}/research-map`,
      source: '找 TA 主題',
    }
  }
  const brand = brands.find((item) => item.id === schedule.scope_id)
  if (brand) {
    const name = brand.display_name?.trim() || brand.seed_query?.trim() || '未命名品牌'
    return {
      label: name,
      href: '/research',
      source: '研究地圖',
    }
  }
  if (schedule.scope === 'brand') {
    return {
      label: `品牌 ${schedule.scope_id.slice(0, 8)}…`,
      href: '/research',
      source: '研究地圖',
    }
  }
  return {
    label: `主題 ${schedule.scope_id.slice(0, 8)}…`,
    href: '/placement/topics',
    source: '找 TA',
  }
}

/** @deprecated 使用 resolvePlacementScanTarget */
export function resolvePlacementTopicTarget(
  schedule: JobScheduleData,
  topics: PlacementTopicData[],
): { label: string; href: string } {
  const { label, href } = resolvePlacementScanTarget(schedule, topics)
  return { label, href }
}

export function resolveCopyMissionTarget(
  schedule: JobScheduleData,
  missions: CopyMissionData[],
): { label: string; href: string; personaId: string } {
  const mission = missions.find((item) => item.id === schedule.scope_id)
  if (!mission) {
    return {
      label: `任務 ${schedule.scope_id.slice(0, 8)}…`,
      href: '/matrix',
      personaId: '',
    }
  }
  const name = mission.label?.trim() || mission.seed_query?.trim() || '未命名任務'
  return {
    label: name,
    href: `/matrix/missions/${encodeURIComponent(mission.id)}`,
    personaId: mission.persona_id,
  }
}

export function scheduleDisplayTitle(templateType: string): string {
  return scheduleKindMeta(templateType)?.label ?? jobTemplateLabel(templateType)
}