"use client"

import { createContext, useContext, type ReactNode } from "react"

import type { SettingsService } from "@/modules/settings/types"

/**
 * SettingsService React Context
 *
 * 通过页面层注入 SettingsService 实现，组件层使用 useSettingsService() 消费，
 * 避免直接 import 其他业务模块的 actions/data-access。
 */
const SettingsServiceContext = createContext<SettingsService | null>(null)

interface SettingsServiceProviderProps {
  service: SettingsService
  children: ReactNode
}

export function SettingsServiceProvider({
  service,
  children,
}: SettingsServiceProviderProps): ReactNode {
  return (
    <SettingsServiceContext.Provider value={service}>
      {children}
    </SettingsServiceContext.Provider>
  )
}

export function useSettingsService(): SettingsService {
  const ctx = useContext(SettingsServiceContext)
  if (!ctx) {
    throw new Error(
      "useSettingsService must be used within a SettingsServiceProvider"
    )
  }
  return ctx
}
