import type { BackendDataServicePage, BackendRecommendationPlacement, BackendRecommendationResponse, BackendRecommendationSlot, BackendSiteAbout, BackendSiteConsulting, BackendSiteHome } from '@/lib/backend'
import { publicAssetUrl, serverFetchJson } from '@/lib/server-api'

function normalizeRecommendationSlot(slot: BackendRecommendationSlot): BackendRecommendationSlot {
  const source = slot.source
    ? slot.sourceType === 'expert'
      ? { ...slot.source, photoUrl: publicAssetUrl('photoUrl' in slot.source ? slot.source.photoUrl : '') }
      : { ...slot.source, coverUrl: publicAssetUrl('coverUrl' in slot.source ? slot.source.coverUrl : '') }
    : null
  return {
    ...slot,
    imageUrl: publicAssetUrl(slot.imageUrl),
    imageUrlOverride: publicAssetUrl(slot.imageUrlOverride),
    source,
  } as BackendRecommendationSlot
}

function normalizeRecommendationResponse(result: BackendRecommendationResponse): BackendRecommendationResponse {
  return {
    placements: Object.fromEntries(Object.entries(result.placements || {}).map(([key, slots]) => [
      key,
      (slots || []).map(normalizeRecommendationSlot),
    ])) as BackendRecommendationResponse['placements'],
    items: (result.items || []).map(normalizeRecommendationSlot),
  }
}

function normalizeHome(home: BackendSiteHome): BackendSiteHome {
  return {
    slides: (home.slides || []).map((slide) => ({ ...slide, imageUrl: publicAssetUrl(slide.imageUrl) })),
    loginSlides: (home.loginSlides || []).map((slide) => ({ ...slide, imageUrl: publicAssetUrl(slide.imageUrl) })),
    assets: (home.assets || []).map((asset) => ({ ...asset, imageUrl: publicAssetUrl(asset.imageUrl) })),
    featuredExperts: (home.featuredExperts || []).map((expert) => ({ ...expert, photoUrl: publicAssetUrl(expert.photoUrl) })),
    blocks: (home.blocks || []).map((block) => ({
      ...block,
      items: (block.items || []).map((item) => ({ ...item, imageUrl: publicAssetUrl(item.imageUrl) })),
    })),
    recommendations: {
      news: (home.recommendations?.news || []).map(normalizeRecommendationSlot),
      courses: (home.recommendations?.courses || []).map(normalizeRecommendationSlot),
      events: (home.recommendations?.events || []).map(normalizeRecommendationSlot),
      experts: (home.recommendations?.experts || []).map(normalizeRecommendationSlot),
    },
  }
}

function normalizeDataServicePage(page: BackendDataServicePage): BackendDataServicePage {
  return {
    blocks: (page.blocks || []).map((block) => ({
      ...block,
      items: (block.items || []).map((item) => ({ ...item, imageUrl: publicAssetUrl(item.imageUrl) })),
    })),
    assets: (page.assets || []).map((asset) => ({ ...asset, imageUrl: publicAssetUrl(asset.imageUrl) })),
  }
}

function normalizeAbout(about: BackendSiteAbout): BackendSiteAbout {
  const normalizeItem = (item: BackendSiteAbout['honors'][number]) => ({ ...item, imageUrl: publicAssetUrl(item.imageUrl) })
  return {
    ...about,
    content: {
      ...about.content,
      heroCoverUrl: publicAssetUrl(about.content?.heroCoverUrl),
      workImageUrl: publicAssetUrl(about.content?.workImageUrl),
    },
    workSteps: (about.workSteps || []).map(normalizeItem),
    serviceObjects: (about.serviceObjects || []).map(normalizeItem),
    representativeWork: (about.representativeWork || []).map(normalizeItem),
    cooperationModes: (about.cooperationModes || []).map(normalizeItem),
    honors: (about.honors || []).map(normalizeItem),
    partners: (about.partners || []).map(normalizeItem),
    team: (about.team || []).map(normalizeItem),
  }
}

function normalizeConsulting(site: BackendSiteConsulting): BackendSiteConsulting {
  return {
    ...site,
    content: {
      ...site.content,
      heroImageUrl: publicAssetUrl(site.content?.heroImageUrl),
    },
    directions: (site.directions || []).map((item) => ({ ...item, imageUrl: publicAssetUrl(item.imageUrl) })),
    cases: (site.cases || []).map((item) => ({ ...item, imageUrl: publicAssetUrl(item.imageUrl) })),
    steps: site.steps || [],
    optionSets: site.optionSets || [],
  }
}

export async function getSiteHome(): Promise<BackendSiteHome> {
  const data = await serverFetchJson<BackendSiteHome>('/site/home')
  return data ? normalizeHome(data) : { slides: [], loginSlides: [], assets: [], featuredExperts: [], blocks: [], recommendations: { news: [], courses: [], events: [], experts: [] } }
}

export async function getSiteRecommendations(placements: BackendRecommendationPlacement[]): Promise<BackendRecommendationResponse> {
  const query = new URLSearchParams()
  if (placements.length) query.set('placements', placements.join(','))
  const data = await serverFetchJson<BackendRecommendationResponse>(`/site/recommendations${query.toString() ? `?${query}` : ''}`)
  return data ? normalizeRecommendationResponse(data) : { placements: {}, items: [] }
}

export async function getDataServicePage(): Promise<BackendDataServicePage> {
  const data = await serverFetchJson<BackendDataServicePage>('/data-service/page')
  return data ? normalizeDataServicePage(data) : { blocks: [], assets: [] }
}

export async function getSiteAbout(): Promise<BackendSiteAbout | null> {
  const data = await serverFetchJson<BackendSiteAbout>('/site/about')
  return data ? normalizeAbout(data) : null
}

export async function getSiteConsulting(): Promise<BackendSiteConsulting | null> {
  const data = await serverFetchJson<BackendSiteConsulting>('/site/consulting')
  return data ? normalizeConsulting(data) : null
}
