"use client"

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

import type { AnnouncementsService } from "../types"
import { defaultAnnouncementsService } from "./default-announcements-service"

/**
 * P1-3: 公告服务 React Context。
 *
 * 通过页面层注入 AnnouncementsService 实现，组件层使用 useAnnouncementsService() 消费，
 * 避免直接 import 业务模块的 actions，实现完全解耦：
 * - 默认实现调用真实 Server Actions
 * - 测试时可注入 mock 实现
 * - 不同角色可注入不同实现
 *
 * 未包裹 Provider 时回退到默认实现，保证向后兼容。
 */
const AnnouncementsServiceContext = createContext<AnnouncementsService | null>(null)

interface AnnouncementsServiceProviderProps {
  /** 注入的服务实现；不传则使用默认实现（调用真实 Server Actions） */
  service?: AnnouncementsService
  children: ReactNode
}

export function AnnouncementsServiceProvider({
  service,
  children,
}: AnnouncementsServiceProviderProps): ReactNode {
  const value = service ?? defaultAnnouncementsService
  return (
    <AnnouncementsServiceContext.Provider value={value}>
      {children}
    </AnnouncementsServiceContext.Provider>
  )
}

export function useAnnouncementsService(): AnnouncementsService {
  const ctx = useContext(AnnouncementsServiceContext)
  return ctx ?? defaultAnnouncementsService
}
