import { ApiRequestError } from '../../lib/http'
import type {
  AdminDashboardResponse,
  AdminRiskFlag,
  AdminRiskFlagsResponse,
  AdminSeasonDetailResponse,
  AdminSeasonListItem,
  AdminSiteSettingsResponse,
  DatabaseHealthResponse,
  OverviewResponse,
  SeasonCategoriesResponse,
  WinnerArchiveResponse,
} from '../../types/awards'

export type ApiMode = 'api' | 'fallback'
export type PublicErrorKind = 'offline' | 'unreachable' | 'server' | null

export function createEmptyOverview(): OverviewResponse {
  return {
    seasonId: 0,
    year: new Date().getFullYear(),
    title: '',
    showDate: '',
    showStartsAt: '20:00:00',
    showStreamUrl: '',
    currentPhase: '',
    isCommunityOnly: true,
    loginProvider: 'Twitch',
    timeline: [],
    featuredCategories: [],
    winnersPreview: [],
    archiveYears: [],
    siteContent: {
      hostDisplayName: '',
      hostTagline: '',
      newsletterUrl: '',
      privacyEmail: '',
      privacyPolicyContent: '',
      socialLinks: [],
      footerLinks: [],
    },
    faq: [],
  }
}

export function createEmptyCategories(): SeasonCategoriesResponse {
  return {
    seasonId: 0,
    year: new Date().getFullYear(),
    categories: [],
  }
}

export function createEmptyArchive(year = new Date().getFullYear() - 1): WinnerArchiveResponse {
  return {
    year,
    items: [],
  }
}

export function createEmptyAdminDashboard(): AdminDashboardResponse {
  return {
    metrics: [],
    activities: [],
    topCategories: [],
    riskFlags: [],
    auditEntries: [],
  }
}

export function createEmptyAdminRiskFlagsResponse(): AdminRiskFlagsResponse {
  return {
    items: [],
    totalCount: 0,
    returnedCount: 0,
    offset: 0,
    limit: 25,
    hasMore: false,
    severityCounts: [],
    statusCounts: [],
  }
}

export function createEmptyAdminSeasonDetail(): AdminSeasonDetailResponse {
  return {
    id: 0,
    year: 0,
    name: '',
    showStreamUrl: '',
    currentPhase: '',
    isCurrent: false,
    isCommunityOnly: true,
    nominationStartsAt: '',
    nominationEndsAt: '',
    votingStartsAt: '',
    votingEndsAt: '',
    reviewStartsAt: '',
    reviewEndsAt: '',
    showDate: '',
    showStartsAt: '20:00:00',
    categories: [],
    candidates: [],
    pendingNominations: [],
    reviewedNominations: [],
    results: [],
    clipSubmissions: [],
  }
}

export function createEmptyAdminSiteSettings(): AdminSiteSettingsResponse {
  return {
    hostDisplayName: '',
    hostTagline: '',
    newsletterUrl: '',
    privacyEmail: '',
    privacyPolicyContent: '',
    privacyPolicyUpdatedBy: null,
    privacyPolicyUpdatedAt: null,
    imprintUrl: '',
    imprintContent: '',
    contactUrl: '',
    contactContent: '',
    sponsorsUrl: '',
    sponsorsContent: '',
    socialLinks: [],
    faq: [],
  }
}

export function createEmptyDatabaseHealth(): DatabaseHealthResponse {
  return {
    provider: 'postgres',
    canConnect: false,
    pendingMigrations: [],
    configuredConnection: {
      source: 'unknown',
    },
  }
}

export function createAwardsState() {
  return {
    overview: createEmptyOverview(),
    categories: createEmptyCategories(),
    archive: createEmptyArchive(),
    admin: createEmptyAdminDashboard(),
    adminSeasons: [] as AdminSeasonListItem[],
    adminSeasonDetail: createEmptyAdminSeasonDetail(),
    adminSiteSettings: createEmptyAdminSiteSettings(),
    adminRiskHistory: [] as AdminRiskFlag[],
    adminRiskFlagsPage: createEmptyAdminRiskFlagsResponse(),
    adminRiskHistoryPage: createEmptyAdminRiskFlagsResponse(),
    databaseHealth: createEmptyDatabaseHealth(),
    adminSelectedSeasonId: null as number | null,
    loading: false,
    apiMode: 'fallback' as ApiMode,
    lastPublicError: null as string | null,
    lastPublicErrorKind: null as PublicErrorKind,
  }
}

/**
 * Guarantee the array fields exist even if a (possibly older) backend omits them,
 * so views can safely read `.length`/`.filter` without crashing the render.
 */
export function normalizeSeasonDetail(detail: AdminSeasonDetailResponse): AdminSeasonDetailResponse {
  return {
    ...detail,
    categories: detail.categories ?? [],
    candidates: detail.candidates ?? [],
    pendingNominations: detail.pendingNominations ?? [],
    reviewedNominations: detail.reviewedNominations ?? [],
    results: detail.results ?? [],
    clipSubmissions: detail.clipSubmissions ?? [],
  }
}

export function classifyPublicLoadError(error: unknown) {
  const message = error instanceof Error ? error.message : 'Die Landingpage konnte nicht geladen werden.'
  const isOffline = typeof navigator !== 'undefined' && navigator.onLine === false
  const isUnreachable = message.toLowerCase().includes('api nicht erreichbar')
  const isServerError = error instanceof ApiRequestError && error.status !== null && error.status >= 500

  return {
    message,
    kind: isOffline ? 'offline' : isServerError ? 'server' : isUnreachable ? 'unreachable' : null,
  } satisfies { message: string; kind: PublicErrorKind }
}
