"use server"

/**
 * 设置模块服务层 Server Actions
 *
 * 这些 wrapper 函数将 users/messaging 模块的 Server Action 适配为
 * SettingsService 接口所需的签名，使其可作为 Server Action 引用
 * 直接传递给 Client Components（Next.js 要求传递给 Client Component
 * 的函数必须是 "use server" 标记的 Server Action）。
 */

import { revalidatePath } from "next/cache"

import type { ActionState } from "@/shared/types/action-state"
import { requirePermission, PermissionDeniedError } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { updateUserProfile } from "@/modules/users/actions"
import type { UpdateUserProfileInput } from "@/modules/users/data-access"
import {
  upsertNotificationPreferences,
} from "@/modules/notifications/preferences"
import type {
  NotificationPreferences,
  UpdateNotificationPreferencesInput,
} from "@/modules/notifications/types"

/**
 * 更新用户资料（Server Action wrapper）
 *
 * 直接委托给 users 模块的 updateUserProfile，保持 Server Action 引用语义。
 */
export async function updateProfileAction(
  input: UpdateUserProfileInput
): Promise<ActionState<void>> {
  return updateUserProfile(input)
}

/**
 * 更新通知偏好（Server Action wrapper）
 *
 * 将 UpdateNotificationPreferencesInput 直接传递给 data-access 层，
 * 绕过 messaging/actions.ts 中基于 FormData 的签名，以适配 SettingsService 接口。
 */
export async function updateNotificationPreferencesAction(
  input: UpdateNotificationPreferencesInput
): Promise<ActionState<NotificationPreferences>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_READ)

    const updated = await upsertNotificationPreferences(ctx.userId, input)
    if (!updated) {
      return { success: false, message: "Failed to update notification preferences" }
    }

    revalidatePath("/settings")

    return { success: true, message: "Notification preferences updated", data: updated }
  } catch (e) {
    if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
    if (e instanceof Error) return { success: false, message: e.message }
    return { success: false, message: "Unexpected error" }
  }
}
