"use server"

import { revalidatePath } from "next/cache"
import { getTranslations } from "next-intl/server"
import { PermissionDeniedError, requirePermission } from "@/shared/lib/auth-guard"
import { trackEvent } from "@/shared/lib/track-event"
import { Permissions } from "@/shared/types/permissions"
import type { AuthContext } from "@/shared/types/permissions"
import type { ActionState } from "@/shared/types/action-state"
import { sendNotification } from "@/modules/notifications/dispatcher"

import {
  SendMessageSchema,
  MessageIdSchema,
  MessageDraftSchema,
  BulkMessageIdsSchema,
  MessageTemplateSchema,
  SendGroupMessageSchema,
  ReportMessageSchema,
  BlockUserSchema,
} from "./schema"
import {
  getMessages,
  getMessageById,
  getMessageThread,
  createMessage,
  markMessageAsRead,
  deleteMessage,
  getRecipients,
  getUnreadMessageCount,
  toggleMessageStar,
  getMessageDrafts,
  createMessageDraft,
  updateMessageDraft,
  deleteMessageDraft,
  isReceiverAllowed,
  bulkMarkMessagesAsRead,
  bulkDeleteMessages,
  bulkToggleMessagesStar,
  recallMessage,
  getMessageTemplates,
  createMessageTemplate,
  updateMessageTemplate,
  deleteMessageTemplate,
  sendGroupMessage,
  reportMessage,
  hasUserReportedMessage,
  blockUser,
  unblockUser,
  isEitherUserBlocked,
  getUserBlocks,
  getMessageAttachments,
} from "./data-access"
import type { Message, MessageType, MessageDraft, MessageTemplate, RecipientOption, UserBlock, MessageAttachment } from "./types"

export async function sendMessageAction(
  prevState: ActionState<string> | null,
  formData: FormData
): Promise<ActionState<string>> {
  let ctx: AuthContext | null = null
  let parsedInput: {
    receiverId: string
    subject: string | null
    content: string
    parentMessageId: string | null
  } | null = null
  try {
    ctx = await requirePermission(Permissions.MESSAGE_SEND)

    const parsed = SendMessageSchema.safeParse({
      receiverId: formData.get("receiverId"),
      subject: formData.get("subject") || undefined,
      content: formData.get("content"),
      parentMessageId: formData.get("parentMessageId") || undefined,
    })

    if (!parsed.success) {
      return { success: false, message: "Invalid form data", errors: parsed.error.flatten().fieldErrors }
    }

    const input = parsed.data
    parsedInput = input
    if (input.receiverId === ctx.userId) {
      return { success: false, message: "Cannot send a message to yourself" }
    }

    // P0-1: Server Action 二次校验收件人是否在 sender 的 DataScope 允许范围内
    // 防止绕过前端 Select 直接构造 FormData 提交任意 receiverId 越权发送
    const allowed = await isReceiverAllowed(ctx.userId, input.receiverId, ctx.dataScope)
    if (!allowed) {
      return { success: false, message: "Recipient not allowed" }
    }

    // P2-5: 屏蔽校验 —— 发送方或接收方任一屏蔽对方，则禁止发送
    const blocked = await isEitherUserBlocked(ctx.userId, input.receiverId)
    if (blocked) {
      return { success: false, message: "Cannot send message due to block" }
    }

    // P0-6: 校验 parentMessageId 属于当前用户参与的会话
    // 防止将回复消息注入到他人会话线程
    if (input.parentMessageId) {
      const parent = await getMessageById(input.parentMessageId, ctx.userId)
      if (!parent) {
        return { success: false, message: "Parent message not accessible" }
      }
    }

    const id = await createMessage({
      senderId: ctx.userId,
      receiverId: input.receiverId,
      subject: input.subject,
      content: input.content,
      parentMessageId: input.parentMessageId,
    })

    // Notify the receiver about the new message via the notifications dispatcher.
    // This respects user notification preferences (SMS/WeChat/Email/In-App).
    const t = await getTranslations("messages")
    const notifyTitle = input.subject
      ? t("notification.messageTitle", { subject: input.subject })
      : t("notification.messageTitleNoSubject")
    await sendNotification({
      userId: input.receiverId,
      type: "info",
      title: notifyTitle,
      content: input.content.slice(0, 200),
      actionUrl: `/messages/${id}`,
      metadata: { messageType: "message", messageId: id },
    })

    revalidatePath("/messages")
    revalidatePath(`/messages/${id}`)

    void trackEvent({
      event: "message.sent",
      userId: ctx.userId,
      targetId: id,
      targetType: "message",
      properties: { receiverId: input.receiverId, hasSubject: !!input.subject },
    })

    return { success: true, message: "Message sent", data: id }
  } catch (e) {
    // P1-9: 失败埋点（权限拒绝除外，避免噪音）
    if (ctx && parsedInput && !(e instanceof PermissionDeniedError)) {
      void trackEvent({
        event: "message.send_failed",
        userId: ctx.userId,
        targetType: "message",
        properties: {
          receiverId: parsedInput.receiverId,
          reason: e instanceof Error ? e.message : "unknown",
        },
      })
    }
    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" }
  }
}

export async function markMessageAsReadAction(messageId: string): Promise<ActionState<string>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_READ)

    const parsed = MessageIdSchema.safeParse({ messageId })
    if (!parsed.success) {
      return { success: false, message: "Invalid message id", errors: parsed.error.flatten().fieldErrors }
    }

    await markMessageAsRead(parsed.data.messageId, ctx.userId)
    revalidatePath("/messages")
    revalidatePath(`/messages/${parsed.data.messageId}`)

    void trackEvent({
      event: "message.marked_read",
      userId: ctx.userId,
      targetId: parsed.data.messageId,
      targetType: "message",
    })

    return { success: true, message: "Marked as read" }
  } 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" }
  }
}

export async function deleteMessageAction(messageId: string): Promise<ActionState<string>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_DELETE)

    const parsed = MessageIdSchema.safeParse({ messageId })
    if (!parsed.success) {
      return { success: false, message: "Invalid message id", errors: parsed.error.flatten().fieldErrors }
    }

    await deleteMessage(parsed.data.messageId, ctx.userId)
    revalidatePath("/messages")
    revalidatePath(`/messages/${parsed.data.messageId}`)

    void trackEvent({
      event: "message.deleted",
      userId: ctx.userId,
      targetId: parsed.data.messageId,
      targetType: "message",
    })

    return { success: true, message: "Message deleted" }
  } 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" }
  }
}

export async function getMessagesAction(
  params: {
    type: MessageType
    page?: number
    pageSize?: number
    keyword?: string
    starredOnly?: boolean
    /** P2-11: 按发件人筛选 */
    senderId?: string
    /** P2-11: 按日期范围筛选 */
    dateFrom?: string
    dateTo?: string
    /** P2-11: 按已读状态筛选 */
    isRead?: boolean
  }
): Promise<ActionState<{ items: Message[]; total: number; page: number; pageSize: number; totalPages: number }>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_READ)
    const result = await getMessages({ userId: ctx.userId, ...params })
    return { success: true, data: result }
  } 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" }
  }
}

/**
 * P1-3: 获取消息线程（根消息 + 回复链）。
 *
 * 替代直接调用 data-access.getMessageThread，统一通过 Server Action 入口
 * 做权限校验。返回的 Message[] 已按时间倒序（与 data-access 一致），
 * UI 层可按需 reverse 为正序展示。
 *
 * 注：原 getMessageDetailAction 已删除（P0-4 死代码，详情数据由
 * getMessageDetailPageData 编排函数 + RSC 直接获取，组件通过 props 接收）。
 */
export async function getMessageThreadAction(messageId: string): Promise<ActionState<Message[]>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_READ)

    const parsed = MessageIdSchema.safeParse({ messageId })
    if (!parsed.success) {
      return { success: false, message: "Invalid message id", errors: parsed.error.flatten().fieldErrors }
    }

    // data-access.getMessageThread 内部会校验当前用户对根消息的访问权
    const thread = await getMessageThread(parsed.data.messageId, ctx.userId)
    return { success: true, data: thread }
  } 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" }
  }
}

export async function getRecipientsAction(): Promise<ActionState<RecipientOption[]>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_SEND)
    const recipients = await getRecipients(ctx.userId, ctx.dataScope)
    return { success: true, data: recipients }
  } 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" }
  }
}

export async function getUnreadMessageCountAction(): Promise<ActionState<number>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_READ)
    const count = await getUnreadMessageCount(ctx.userId)
    return { success: true, data: count }
  } 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" }
  }
}

// ---------------------------------------------------------------------------
// V2-P2-13c: 消息星标 Server Actions
// ---------------------------------------------------------------------------

export async function toggleMessageStarAction(messageId: string): Promise<ActionState<string>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_READ)

    const parsed = MessageIdSchema.safeParse({ messageId })
    if (!parsed.success) {
      return { success: false, message: "Invalid message id", errors: parsed.error.flatten().fieldErrors }
    }

    await toggleMessageStar(parsed.data.messageId, ctx.userId)
    revalidatePath("/messages")
    revalidatePath(`/messages/${parsed.data.messageId}`)

    void trackEvent({
      event: "message.star_toggled",
      userId: ctx.userId,
      targetId: parsed.data.messageId,
      targetType: "message",
    })

    return { success: true, message: "Star toggled" }
  } 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" }
  }
}

// ---------------------------------------------------------------------------
// V2-P2-13c: 消息草稿 Server Actions
// ---------------------------------------------------------------------------

export async function getMessageDraftsAction(): Promise<ActionState<MessageDraft[]>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_SEND)
    const drafts = await getMessageDrafts(ctx.userId)
    return { success: true, data: drafts }
  } 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" }
  }
}

export async function saveMessageDraftAction(
  prevState: ActionState<string> | null,
  formData: FormData
): Promise<ActionState<string>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_SEND)

    const parsed = MessageDraftSchema.safeParse({
      draftId: formData.get("draftId") ?? undefined,
      receiverId: formData.get("receiverId") ?? undefined,
      subject: formData.get("subject") ?? undefined,
      content: formData.get("content") ?? undefined,
      parentMessageId: formData.get("parentMessageId") ?? undefined,
    })

    if (!parsed.success) {
      return { success: false, message: "Invalid form data", errors: parsed.error.flatten().fieldErrors }
    }

    const input = parsed.data
    // P2-10: 从 FormData 读取 deviceId 和 expectedVersion（可选）
    const deviceId = (formData.get("deviceId") as string | null) ?? null
    const expectedVersionRaw = formData.get("expectedVersion")
    const expectedVersion = expectedVersionRaw ? Number(expectedVersionRaw) : undefined

    const draftData = {
      receiverId: input.receiverId || null,
      subject: input.subject || null,
      content: input.content || null,
      parentMessageId: input.parentMessageId || null,
      deviceId,
      expectedVersion,
    }

    if (input.draftId) {
      // P2-10: updateMessageDraft 现在返回 "ok" | "not_found" | "conflict"
      const result = await updateMessageDraft(input.draftId, ctx.userId, draftData)
      if (result === "conflict") {
        // P2-10: 版本冲突，客户端应拉取最新版本
        return { success: false, message: "Draft version conflict" }
      }
      if (result === "not_found") {
        // P2-10: 草稿不存在（可能已在其他设备删除），重新创建
        const id = await createMessageDraft({
          userId: ctx.userId,
          receiverId: draftData.receiverId,
          subject: draftData.subject,
          content: draftData.content,
          parentMessageId: draftData.parentMessageId,
          deviceId: draftData.deviceId,
        })
        return { success: true, message: "Draft recreated", data: id }
      }
      return { success: true, message: "Draft saved", data: input.draftId }
    }

    const id = await createMessageDraft({
      userId: ctx.userId,
      receiverId: draftData.receiverId,
      subject: draftData.subject,
      content: draftData.content,
      parentMessageId: draftData.parentMessageId,
      deviceId: draftData.deviceId,
    })

    return { success: true, message: "Draft created", data: id }
  } 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" }
  }
}

export async function deleteMessageDraftAction(draftId: string): Promise<ActionState<string>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_SEND)

    await deleteMessageDraft(draftId, ctx.userId)
    revalidatePath("/messages/compose")

    return { success: true, message: "Draft deleted" }
  } 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" }
  }
}

// ---------------------------------------------------------------------------
// P2-1: 批量操作 Server Actions
// ---------------------------------------------------------------------------

export async function bulkMarkMessagesAsReadAction(
  ids: string[]
): Promise<ActionState<{ updated: number }>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_READ)

    const parsed = BulkMessageIdsSchema.safeParse({ ids })
    if (!parsed.success) {
      return { success: false, message: "Invalid message IDs", errors: parsed.error.flatten().fieldErrors }
    }

    const updated = await bulkMarkMessagesAsRead(parsed.data.ids, ctx.userId)
    revalidatePath("/messages")

    void trackEvent({
      event: "message.marked_read",
      userId: ctx.userId,
      targetType: "message",
      properties: { count: updated, bulk: true },
    })

    return { success: true, message: "Messages marked as read", 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" }
  }
}

export async function bulkDeleteMessagesAction(
  ids: string[]
): Promise<ActionState<string>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_DELETE)

    const parsed = BulkMessageIdsSchema.safeParse({ ids })
    if (!parsed.success) {
      return { success: false, message: "Invalid message IDs", errors: parsed.error.flatten().fieldErrors }
    }

    await bulkDeleteMessages(parsed.data.ids, ctx.userId)
    revalidatePath("/messages")

    void trackEvent({
      event: "message.deleted",
      userId: ctx.userId,
      targetType: "message",
      properties: { count: parsed.data.ids.length, bulk: true },
    })

    return { success: true, message: "Messages deleted" }
  } 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" }
  }
}

export async function bulkToggleMessagesStarAction(
  ids: string[]
): Promise<ActionState<string>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_READ)

    const parsed = BulkMessageIdsSchema.safeParse({ ids })
    if (!parsed.success) {
      return { success: false, message: "Invalid message IDs", errors: parsed.error.flatten().fieldErrors }
    }

    await bulkToggleMessagesStar(parsed.data.ids, ctx.userId)
    revalidatePath("/messages")

    void trackEvent({
      event: "message.star_toggled",
      userId: ctx.userId,
      targetType: "message",
      properties: { count: parsed.data.ids.length, bulk: true },
    })

    return { success: true, message: "Star toggled" }
  } 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" }
  }
}

// ---------------------------------------------------------------------------
// P2-4: 消息撤回 Server Action（2 分钟窗口内仅发送方可撤回）
// ---------------------------------------------------------------------------

export async function recallMessageAction(
  messageId: string
): Promise<ActionState<string>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_SEND)

    const parsed = MessageIdSchema.safeParse({ messageId })
    if (!parsed.success) {
      return { success: false, message: "Invalid message id", errors: parsed.error.flatten().fieldErrors }
    }

    const result = await recallMessage(parsed.data.messageId, ctx.userId)

    if (result === "not_found") {
      return { success: false, message: "Message not found or not owned" }
    }
    if (result === "already_recalled") {
      return { success: false, message: "Message already recalled" }
    }
    if (result === "expired") {
      return { success: false, message: "Recall window expired" }
    }

    revalidatePath("/messages")
    revalidatePath(`/messages/${parsed.data.messageId}`)

    void trackEvent({
      event: "message.recalled",
      userId: ctx.userId,
      targetId: parsed.data.messageId,
      targetType: "message",
    })

    return { success: true, message: "Message recalled" }
  } 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" }
  }
}

// ---------------------------------------------------------------------------
// P2-2: 群组消息 Server Action（教师→全班家长，fan-out on write）
// ---------------------------------------------------------------------------

export async function sendGroupMessageAction(
  prevState: ActionState<{ recipientCount: number }> | null,
  formData: FormData
): Promise<ActionState<{ recipientCount: number }>> {
  let ctx: AuthContext | null = null
  let parsedInput: { classId: string; subject: string | null; content: string } | null = null
  try {
    ctx = await requirePermission(Permissions.MESSAGE_SEND)

    const parsed = SendGroupMessageSchema.safeParse({
      classId: formData.get("classId"),
      subject: formData.get("subject") || undefined,
      content: formData.get("content"),
    })

    if (!parsed.success) {
      return { success: false, message: "Invalid form data", errors: parsed.error.flatten().fieldErrors }
    }

    const input = parsed.data
    parsedInput = input

    // P2-2: 校验当前教师是否有权向该班级群发（必须在其 class_taught 范围内）
    const allowed = ctx.dataScope.type === "class_taught"
      && ctx.dataScope.classIds.includes(input.classId)
    if (!allowed) {
      return { success: false, message: "Not allowed to send group message to this class" }
    }

    const result = await sendGroupMessage({
      senderId: ctx.userId,
      classId: input.classId,
      subject: input.subject,
      content: input.content,
    })

    if (result.recipientIds.length === 0) {
      return { success: false, message: "No recipients found in this class" }
    }

    // 通知每个家长
    const t = await getTranslations("messages")
    const notifyTitle = input.subject
      ? t("notification.messageTitle", { subject: input.subject })
      : t("notification.messageTitleNoSubject")
    const notifyContent = input.content.slice(0, 200)

    await Promise.all(
      result.recipientIds.map((parentId) =>
        sendNotification({
          userId: parentId,
          type: "info",
          title: notifyTitle,
          content: notifyContent,
          actionUrl: "/messages",
          metadata: { messageType: "group_message", groupMessageId: result.groupMessageId },
        })
      )
    )

    revalidatePath("/messages")

    void trackEvent({
      event: "message.group_sent",
      userId: ctx.userId,
      targetType: "message",
      properties: {
        classId: input.classId,
        recipientCount: result.recipientIds.length,
        groupMessageId: result.groupMessageId,
      },
    })

    return {
      success: true,
      message: "Group message sent",
      data: { recipientCount: result.recipientIds.length },
    }
  } catch (e) {
    // P1-9: 失败埋点（权限拒绝除外）
    if (ctx && parsedInput && !(e instanceof PermissionDeniedError)) {
      void trackEvent({
        event: "message.group_send_failed",
        userId: ctx.userId,
        targetType: "message",
        properties: {
          classId: parsedInput.classId,
          reason: e instanceof Error ? e.message : "unknown",
        },
      })
    }
    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" }
  }
}

// ---------------------------------------------------------------------------
// P2-6: 快捷回复模板 Server Actions
// ---------------------------------------------------------------------------

export async function getMessageTemplatesAction(): Promise<ActionState<MessageTemplate[]>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_SEND)
    const templates = await getMessageTemplates(ctx.userId)
    return { success: true, data: templates }
  } 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" }
  }
}

export async function saveMessageTemplateAction(
  prevState: ActionState<string> | null,
  formData: FormData
): Promise<ActionState<string>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_SEND)

    const parsed = MessageTemplateSchema.safeParse({
      templateId: formData.get("templateId") ?? undefined,
      title: formData.get("title"),
      content: formData.get("content"),
      sortOrder: formData.get("sortOrder") !== null
        ? Number(formData.get("sortOrder"))
        : undefined,
    })

    if (!parsed.success) {
      return { success: false, message: "Invalid form data", errors: parsed.error.flatten().fieldErrors }
    }

    const input = parsed.data

    if (input.templateId) {
      await updateMessageTemplate(input.templateId, ctx.userId, {
        title: input.title,
        content: input.content,
        sortOrder: input.sortOrder,
      })
      revalidatePath("/messages/compose")
      return { success: true, message: "Template updated", data: input.templateId }
    }

    const id = await createMessageTemplate({
      userId: ctx.userId,
      title: input.title,
      content: input.content,
      sortOrder: input.sortOrder,
    })

    revalidatePath("/messages/compose")

    void trackEvent({
      event: "message.template_created",
      userId: ctx.userId,
      targetId: id,
      targetType: "message",
    })

    return { success: true, message: "Template created", data: id }
  } 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" }
  }
}

export async function deleteMessageTemplateAction(templateId: string): Promise<ActionState<string>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_SEND)

    const parsed = MessageIdSchema.safeParse({ messageId: templateId })
    if (!parsed.success) {
      return { success: false, message: "Invalid template id", errors: parsed.error.flatten().fieldErrors }
    }

    await deleteMessageTemplate(parsed.data.messageId, ctx.userId)
    revalidatePath("/messages/compose")

    return { success: true, message: "Template deleted" }
  } 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" }
  }
}

// ---------------------------------------------------------------------------
// 通知相关 Server Actions（getNotificationsAction / markNotificationAsReadAction /
// markAllNotificationsAsReadAction / getUnreadNotificationCountAction /
// getNotificationPreferencesAction / updateNotificationPreferencesAction）
// 已迁移至 @/modules/notifications/actions。请直接从 notifications 模块导入。
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// P2-5: 消息举报 + 用户屏蔽 Server Actions
// ---------------------------------------------------------------------------

/**
 * P2-5: 举报消息。
 *
 * - 校验消息存在且当前用户为接收方（只能举报收到的消息）
 * - 防重复：同一用户对同一消息只能举报一次
 */
export async function reportMessageAction(
  prevState: ActionState<null> | null,
  formData: FormData
): Promise<ActionState<null>> {
  let ctx: AuthContext | null = null
  let parsedInput: { messageId: string; reason: string; description?: string } | null = null
  try {
    ctx = await requirePermission(Permissions.MESSAGE_READ)

    const parsed = ReportMessageSchema.safeParse({
      messageId: formData.get("messageId"),
      reason: formData.get("reason"),
      description: formData.get("description") || undefined,
    })

    if (!parsed.success) {
      return { success: false, message: "Invalid form data", errors: parsed.error.flatten().fieldErrors }
    }

    const input = parsed.data
    parsedInput = input

    // 校验消息存在且当前用户为接收方（防越权举报）
    const msg = await getMessageById(input.messageId, ctx.userId)
    if (!msg) {
      return { success: false, message: "Message not found" }
    }
    // 举报人必须是接收方（不能举报自己发的消息）
    if (msg.senderId === ctx.userId) {
      return { success: false, message: "Cannot report your own message" }
    }

    const result = await reportMessage({
      reporterId: ctx.userId,
      messageId: input.messageId,
      reportedUserId: msg.senderId,
      reason: input.reason as "spam" | "harassment" | "inappropriate" | "other",
      description: input.description ?? null,
    })

    if (result === "already_reported") {
      return { success: false, message: "Already reported this message" }
    }

    void trackEvent({
      event: "message.reported",
      userId: ctx.userId,
      targetId: input.messageId,
      targetType: "message",
      properties: { reason: input.reason },
    })

    return { success: true, message: "Message reported", data: null }
  } catch (e) {
    if (ctx && parsedInput && !(e instanceof PermissionDeniedError)) {
      void trackEvent({
        event: "message.report_failed",
        userId: ctx.userId,
        targetId: parsedInput.messageId,
        targetType: "message",
        properties: { reason: parsedInput.reason },
      })
    }
    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" }
  }
}

/**
 * P2-5: 检查当前用户是否已举报某条消息（用于 UI 禁用状态）。
 */
export async function checkReportedAction(messageId: string): Promise<ActionState<boolean>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_READ)
    const reported = await hasUserReportedMessage(ctx.userId, messageId)
    return { success: true, data: reported }
  } 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" }
  }
}

/**
 * P2-5: 屏蔽用户。
 */
export async function blockUserAction(
  prevState: ActionState<null> | null,
  formData: FormData
): Promise<ActionState<null>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_SEND)

    const parsed = BlockUserSchema.safeParse({
      blockedId: formData.get("blockedId"),
    })

    if (!parsed.success) {
      return { success: false, message: "Invalid form data", errors: parsed.error.flatten().fieldErrors }
    }

    const input = parsed.data

    const result = await blockUser(ctx.userId, input.blockedId)

    if (result === "self_block") {
      return { success: false, message: "Cannot block yourself" }
    }
    if (result === "already_blocked") {
      return { success: false, message: "User already blocked" }
    }

    revalidatePath("/messages")

    void trackEvent({
      event: "message.user_blocked",
      userId: ctx.userId,
      targetId: input.blockedId,
      targetType: "user",
    })

    return { success: true, message: "User blocked", data: null }
  } 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" }
  }
}

/**
 * P2-5: 取消屏蔽用户。
 */
export async function unblockUserAction(blockedId: string): Promise<ActionState<null>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_SEND)
    await unblockUser(ctx.userId, blockedId)
    revalidatePath("/messages")

    void trackEvent({
      event: "message.user_unblocked",
      userId: ctx.userId,
      targetId: blockedId,
      targetType: "user",
    })

    return { success: true, message: "User unblocked", data: null }
  } 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" }
  }
}

/**
 * P2-5: 获取当前用户的屏蔽列表。
 */
export async function getUserBlocksAction(): Promise<ActionState<UserBlock[]>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_SEND)
    const blocks = await getUserBlocks(ctx.userId)
    return { success: true, data: blocks }
  } 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" }
  }
}

// ---------------------------------------------------------------------------
// P2-3: 消息附件 Server Actions
// ---------------------------------------------------------------------------

/**
 * P2-3: 获取指定消息的附件列表。
 *
 * 校验当前用户对消息有访问权（必须是发送方或接收方），防止越权访问附件。
 * 附件存储复用 files 模块的 fileAttachments 表（targetType="message"）。
 */
export async function getMessageAttachmentsAction(
  messageId: string
): Promise<ActionState<MessageAttachment[]>> {
  try {
    const ctx = await requirePermission(Permissions.MESSAGE_READ)
    // 校验访问权：必须是消息的发送方或接收方
    const msg = await getMessageById(messageId, ctx.userId)
    if (!msg) {
      return { success: false, message: "Message not found" }
    }
    const attachments = await getMessageAttachments(messageId)
    return { success: true, data: attachments }
  } 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" }
  }
}
