import { z } from "zod"

export const SendMessageSchema = z
  .object({
    receiverId: z.string().trim().min(1),
    subject: z.string().trim().max(255).optional().nullable(),
    content: z.string().trim().min(1),
    parentMessageId: z.string().trim().optional().nullable(),
  })
  .transform((v) => ({
    receiverId: v.receiverId,
    subject: v.subject && v.subject.length > 0 ? v.subject : null,
    content: v.content,
    parentMessageId:
      v.parentMessageId && v.parentMessageId.length > 0 ? v.parentMessageId : null,
  }))

export type SendMessageInput = z.infer<typeof SendMessageSchema>

/** 校验单个 messageId / notificationId 路径参数 */
export const MessageIdSchema = z.object({
  messageId: z.string().trim().min(1),
})

export type MessageIdInput = z.infer<typeof MessageIdSchema>

/**
 * 校验消息草稿表单（来自 FormData）。
 * 所有字段可选：draftId 存在时为更新，不存在时为创建。
 * 使用 Zod 安全转换 FormData.get() 的 string | File | null 返回值。
 */
export const MessageDraftSchema = z.object({
  draftId: z.string().trim().min(1).optional(),
  receiverId: z.string().trim().min(1).optional(),
  subject: z.string().trim().max(255).optional(),
  content: z.string().max(5000).optional(),
  parentMessageId: z.string().trim().min(1).optional(),
})

export type MessageDraftFormInput = z.infer<typeof MessageDraftSchema>

/** P2-1: 批量操作 ID 列表校验 */
export const BulkMessageIdsSchema = z.object({
  ids: z.array(z.string().trim().min(1)).min(1).max(100),
})

export type BulkMessageIdsInput = z.infer<typeof BulkMessageIdsSchema>

/** P2-6: 快捷回复模板校验（创建/更新） */
export const MessageTemplateSchema = z.object({
  templateId: z.string().trim().min(1).optional(),
  title: z.string().trim().min(1).max(100),
  content: z.string().trim().min(1).max(2000),
  sortOrder: z.number().int().min(0).max(9999).optional(),
})

export type MessageTemplateFormInput = z.infer<typeof MessageTemplateSchema>

/** P2-2: 群组消息校验（教师→全班家长） */
export const SendGroupMessageSchema = z
  .object({
    classId: z.string().trim().min(1),
    subject: z.string().trim().max(255).optional().nullable(),
    content: z.string().trim().min(1),
  })
  .transform((v) => ({
    classId: v.classId,
    subject: v.subject && v.subject.length > 0 ? v.subject : null,
    content: v.content,
  }))

export type SendGroupMessageInput = z.infer<typeof SendGroupMessageSchema>

/** P2-5: 举报消息校验 */
export const ReportMessageSchema = z.object({
  messageId: z.string().trim().min(1),
  reason: z.enum(["spam", "harassment", "inappropriate", "other"]),
  description: z.string().trim().max(1000).optional(),
})

export type ReportMessageFormInput = z.infer<typeof ReportMessageSchema>

/** P2-5: 屏蔽用户校验 */
export const BlockUserSchema = z.object({
  blockedId: z.string().trim().min(1),
})

export type BlockUserFormInput = z.infer<typeof BlockUserSchema>
