import type { AgentCatalogCategory, AgentProduct, AgentWorkflow, Course, CourseAccessState, DataProduct, Event } from '@/types'
import { publicAssetUrl, serverFetchJson } from '@/lib/server-api'

type ProductType = 'membership' | 'course' | 'event' | 'data' | 'agent' | 'expert'

interface BackendProduct {
  id: string
  slug: string
  type: ProductType
  title: string
  summary: string
  priceAmount: number
  status: 'draft' | 'published' | 'offline'
}

interface BackendDataProduct extends BackendProduct {
  category?: '研究报告' | '表格数据' | '政策数据库' | '资料包'
  fileFormat?: 'PDF' | 'Excel' | 'CSV' | 'ZIP'
  coverUrl?: string
  fileUrl?: string
  fileName?: string
  fileSize?: number
  tags?: string[]
  caseGoal?: string
  requestOutline?: string
  deliveryOutline?: string
  serviceNote?: string
  featuredPosition?: number | null
  sortOrder?: number
}

interface BackendCourseProduct extends BackendProduct {
  productStatus?: 'draft' | 'published' | 'offline'
  instructor?: string
  courseType?: 'free' | 'paid' | 'junior' | 'senior'
  memberLevelRequired?: 0 | 1 | 2
  lessonCount?: number
  startsAt?: string | null
  courseStatus?: 'upcoming' | 'ongoing' | 'completed' | 'anytime'
  location?: string
  direction?: string
  courseFormat?: string
  accessPolicy?: Course['accessPolicy']
  registeredAccess?: CourseAccessState
  juniorAccess?: CourseAccessState
  seniorAccess?: CourseAccessState
  registeredPriceAmount?: number
  juniorPriceAmount?: number
  seniorPriceAmount?: number
  coverUrl?: string
  liveUrl?: string
  replayUrl?: string
  coverLabel?: string
  capacity?: number
  registeredCount?: number
  checkinRequired?: boolean
  recommended?: boolean
  audience?: string
  outcomes?: string[]
  modules?: string[]
  lessonModules?: Course['lessonModules']
  accessNote?: string
}

interface BackendEventProduct extends Omit<BackendProduct, 'status'> {
  productStatus?: 'draft' | 'published' | 'offline'
  status?: 'draft' | 'published' | 'registration_closed' | 'offline' | 'deleted'
  eventType?: 'public' | 'pro' | 'max' | 'free'
  topic?: Event['topic']
  eventFormat?: Event['eventFormat']
  coverUrl?: string
  coverLabel?: string
  audience?: string
  highlights?: string[]
  agenda?: string[]
  startsAt?: string | null
  endsAt?: string | null
  location?: string
  isOnline?: boolean
  onlineUrl?: string
  capacity?: number
  registeredCount?: number
  realRegisteredCount?: number
  registrationStatus?: 'not_started' | 'open' | 'closed' | 'full' | 'finished'
  initialRegisteredCount?: number
  registeredAccess?: CourseAccessState
  juniorAccess?: CourseAccessState
  seniorAccess?: CourseAccessState
  registeredPriceAmount?: number
  juniorPriceAmount?: number
  seniorPriceAmount?: number
  memberLevelRequired?: 0 | 1 | 2
  recommended?: boolean
  sortOrder?: number
}

function assetUrl(value?: string | null) {
  return publicAssetUrl(value) || undefined
}

function yuan(cents: number) {
  return Math.round(cents / 100)
}

export async function getCourseProducts(): Promise<Course[]> {
  const data = await serverFetchJson<{ items: BackendCourseProduct[] }>('/courses/catalog')
  return (data?.items || []).map(mapCourseProduct)
}

export async function getCourseProduct(slug: string): Promise<Course | null> {
  const data = await serverFetchJson<BackendCourseProduct>(`/courses/catalog/${encodeURIComponent(slug)}`)
  return data ? mapCourseProduct(data) : null
}

export async function getEventProducts(): Promise<Event[]> {
  const data = await serverFetchJson<{ items: BackendEventProduct[] }>('/events/catalog')
  return (data?.items || []).map(mapEventProduct)
}

export async function getEventProduct(slug: string): Promise<Event | null> {
  const data = await serverFetchJson<BackendEventProduct>(`/events/catalog/${encodeURIComponent(slug)}`)
  return data ? mapEventProduct(data) : null
}

function mapEventProduct(product: BackendEventProduct): Event {
  const startsAt = product.startsAt || new Date(Date.now() + 1000 * 60 * 60 * 24 * 14).toISOString()
  const endsAt = product.endsAt || startsAt
  return {
    id: product.id,
    slug: product.slug,
    title: product.title,
    eventType: product.eventType || (product.priceAmount > 0 ? 'public' : 'free'),
    price: yuan(safeCents(product.priceAmount)),
    memberLevelRequired: product.memberLevelRequired || 0,
    productStatus: product.productStatus,
    status: product.status,
    topic: product.topic,
    eventFormat: product.eventFormat,
    startsAt,
    endsAt,
    location: product.location || '大连市大数据研究院',
    isOnline: Boolean(product.isOnline),
    onlineUrl: product.onlineUrl || '',
    capacity: product.capacity || 0,
    registeredCount: product.registeredCount || 0,
    realRegisteredCount: product.realRegisteredCount || 0,
    registrationStatus: product.registrationStatus,
    initialRegisteredCount: product.initialRegisteredCount || 0,
    summary: product.summary,
    coverUrl: assetUrl(product.coverUrl),
    coverLabel: product.coverLabel || undefined,
    audience: product.audience || undefined,
    highlights: product.highlights || [],
    agenda: product.agenda || [],
    registeredAccess: product.registeredAccess,
    juniorAccess: product.juniorAccess,
    seniorAccess: product.seniorAccess,
    registeredPriceAmount: product.registeredPriceAmount || 0,
    juniorPriceAmount: product.juniorPriceAmount || 0,
    seniorPriceAmount: product.seniorPriceAmount || 0,
    recommended: product.recommended || false,
    sortOrder: product.sortOrder || 0,
  }
}

export async function getDataProducts(): Promise<DataProduct[]> {
  const data = await serverFetchJson<{ items: BackendDataProduct[] }>('/data/catalog')
  return (data?.items || []).map(mapDataProduct)
}

export async function getDataProduct(slug: string): Promise<DataProduct | null> {
  const data = await serverFetchJson<BackendDataProduct>(`/data/catalog/${encodeURIComponent(slug)}`)
  return data ? mapDataProduct(data) : null
}

function inferDataFormat(product: BackendProduct): DataProduct['fileFormat'] {
  return product.title.includes('图谱') ? 'ZIP' : product.title.includes('月报') || product.title.includes('数据库') ? 'Excel' : 'PDF'
}

function mapDataProduct(product: BackendDataProduct): DataProduct {
  return {
    id: product.id,
    slug: product.slug,
    title: product.title,
    category: product.category || '研究报告',
    fileFormat: product.fileFormat || inferDataFormat(product),
    price: yuan(product.priceAmount),
    summary: product.summary,
    coverUrl: assetUrl(product.coverUrl),
    fileUrl: assetUrl(product.fileUrl),
    fileName: product.fileName || undefined,
    fileSize: product.fileSize || 0,
    tags: product.tags || [],
    caseGoal: product.caseGoal || '',
    requestOutline: product.requestOutline || '',
    deliveryOutline: product.deliveryOutline || '',
    serviceNote: product.serviceNote || '',
  }
}

type BackendAgentCatalog = {
  categories: AgentCatalogCategory[]
  workflow: AgentWorkflow | null
  items: Array<BackendProduct & {
    coverUrl?: string
    scenarioTags?: string[]
    detailDescription?: string
    deliveryNote?: string
    registeredAccess?: CourseAccessState
    juniorAccess?: CourseAccessState
    seniorAccess?: CourseAccessState
    registeredPriceAmount?: number
    juniorPriceAmount?: number
    seniorPriceAmount?: number
  }>
}

export async function getAgentCatalog(): Promise<{ categories: AgentCatalogCategory[]; workflow: AgentWorkflow | null; items: AgentProduct[] }> {
  const data = await serverFetchJson<BackendAgentCatalog>('/agents/catalog')
  return {
    categories: data?.categories || [],
    workflow: data?.workflow ? { ...data.workflow, imageUrl: assetUrl(data.workflow.imageUrl) } : null,
    items: (data?.items || []).map(mapAgentProduct),
  }
}

export async function getAgentProducts(): Promise<AgentProduct[]> {
  const catalog = await getAgentCatalog()
  return catalog.items
}

export async function getAgentProduct(slug: string): Promise<AgentProduct | null> {
  const product = await serverFetchJson<BackendProduct & {
    coverUrl?: string
    scenarioTags?: string[]
    detailDescription?: string
    deliveryNote?: string
    registeredAccess?: CourseAccessState
    juniorAccess?: CourseAccessState
    seniorAccess?: CourseAccessState
    registeredPriceAmount?: number
    juniorPriceAmount?: number
    seniorPriceAmount?: number
  }>(`/agents/catalog/${encodeURIComponent(slug)}`)
  return product ? mapAgentProduct(product) : null
}

function safeCents(value: unknown) {
  const amount = Number(value)
  if (!Number.isFinite(amount)) return 0
  return Math.max(0, Math.round(amount))
}

function normalizeAccessState(value: unknown, fallbackPriceAmount: number): CourseAccessState {
  if (value === 'closed' || value === 'free' || value === 'paid') return value
  return fallbackPriceAmount > 0 ? 'paid' : 'free'
}

function mapAgentProduct(product: BackendProduct & {
  coverUrl?: string
  scenarioTags?: string[]
  detailDescription?: string
  deliveryNote?: string
  registeredAccess?: CourseAccessState
  juniorAccess?: CourseAccessState
  seniorAccess?: CourseAccessState
  registeredPriceAmount?: number
  juniorPriceAmount?: number
  seniorPriceAmount?: number
}): AgentProduct {
  const priceAmount = safeCents(product.priceAmount)
  const registeredPriceAmount = safeCents(product.registeredPriceAmount ?? priceAmount)
  const juniorPriceAmount = safeCents(product.juniorPriceAmount ?? priceAmount)
  const seniorPriceAmount = safeCents(product.seniorPriceAmount ?? priceAmount)

  return {
    id: product.id,
    slug: product.slug,
    title: product.title,
    scenarioTags: product.scenarioTags || inferAgentTags(product.title),
    registeredAccess: normalizeAccessState(product.registeredAccess, registeredPriceAmount),
    juniorAccess: normalizeAccessState(product.juniorAccess, juniorPriceAmount),
    seniorAccess: normalizeAccessState(product.seniorAccess, seniorPriceAmount),
    registeredPriceAmount,
    juniorPriceAmount,
    seniorPriceAmount,
    price: yuan(registeredPriceAmount || priceAmount),
    detailDescription: product.detailDescription || '购买后在个人中心提交资料，团队会进入需求审核、配置和交付验收流程。',
    summary: product.summary,
    deliveryNote: product.deliveryNote || '购买后在个人中心提交资料，团队会进入需求审核、配置和交付验收流程。',
    coverUrl: assetUrl(product.coverUrl),
  }
}

function inferAgentTags(title: string) {
  if (title.includes('政策')) return ['政策研究', '产业服务']
  if (title.includes('采购')) return ['采购决策', '供应商评估']
  if (title.includes('合规') || title.includes('安全')) return ['数据安全', '合规审查']
  if (title.includes('资产') || title.includes('治理')) return ['数据治理', '数据资产']
  if (title.includes('园区') || title.includes('产业')) return ['产业服务', '园区运营']
  return ['规划咨询', '报告生成']
}

function mapCourseProduct(product: BackendCourseProduct): Course {
  const accessPolicy = product.accessPolicy || 'paid_all'
  const registeredAccess = product.registeredAccess || (accessPolicy === 'free_all' ? 'free' : accessPolicy === 'paid_all' || accessPolicy === 'member_free_guest_paid' ? 'paid' : 'closed')
  const juniorAccess = product.juniorAccess || (accessPolicy === 'senior_only_free' ? 'closed' : accessPolicy === 'paid_all' || accessPolicy === 'junior_paid_senior_free' ? 'paid' : 'free')
  const seniorAccess = product.seniorAccess || (accessPolicy === 'paid_all' ? 'paid' : 'free')
  const requiredLevel = registeredAccess !== 'closed' ? 0 : juniorAccess !== 'closed' ? 1 : seniorAccess !== 'closed' ? 2 : (product.memberLevelRequired ?? 0)
  return {
    id: product.id,
    slug: product.slug,
    title: product.title,
    instructor: product.instructor || '研究院讲师',
    courseType: product.courseType || (product.priceAmount > 0 ? 'paid' : 'free'),
    price: yuan(product.priceAmount),
    memberLevelRequired: requiredLevel,
    lessonCount: product.lessonCount || 0,
    startsAt: product.startsAt || null,
    status: product.courseStatus || 'anytime',
    summary: product.summary,
    productStatus: product.productStatus || product.status,
    location: product.location || undefined,
    direction: product.direction || undefined,
    courseFormat: product.courseFormat || undefined,
    accessPolicy: product.accessPolicy || 'paid_all',
    registeredAccess,
    juniorAccess,
    seniorAccess,
    registeredPriceAmount: product.registeredPriceAmount ?? product.priceAmount,
    juniorPriceAmount: product.juniorPriceAmount ?? product.priceAmount,
    seniorPriceAmount: product.seniorPriceAmount ?? product.priceAmount,
    coverUrl: assetUrl(product.coverUrl),
    liveUrl: assetUrl(product.liveUrl),
    replayUrl: assetUrl(product.replayUrl),
    coverLabel: product.coverLabel || undefined,
    capacity: product.capacity || 0,
    registeredCount: product.registeredCount || 0,
    checkinRequired: Boolean(product.checkinRequired),
    recommended: Boolean(product.recommended),
    audience: product.audience || undefined,
    outcomes: product.outcomes || [],
    modules: product.modules || [],
    lessonModules: product.lessonModules || [],
    accessNote: product.accessNote || undefined,
  }
}
