import {z} from 'zod'

import {pageQueryShape} from './pagination'

export const DM_MESSAGE_MAX = 1000

export const DmTextSchema = z
  .string()
  .trim()
  .min(1)
  .max(DM_MESSAGE_MAX)

export const SendDmSchema = z.object({
  // client-minted id for an idempotent send: a replayed send whose ack was
  // lost to a dropped connection upserts on this pk instead of doubling
  id: z.uuid().optional(),
  text: DmTextSchema,
})

export const CreateConversationSchema = z.object({
  userId: z.uuid(),
})

// plain text only; dms deliberately have no mention facets
export const DmMessageSchema = z.object({
  id: z.uuid(),
  conversationId: z.uuid(),
  senderId: z.uuid(),
  text: z.string(),
  createdAt: z.iso.datetime(),
})

export const DmPeerSchema = z.object({
  id: z.uuid(),
  handle: z.string(),
  avatarUrl: z.url().nullable(),
})

export const DmConversationSchema = z.object({
  id: z.uuid(),
  peer: DmPeerSchema,
  lastMessage: DmMessageSchema.nullable(),
  lastMessageAt: z.iso.datetime().nullable(),
  unreadCount: z.number().int().nonnegative(),
  // false once the friendship ends — the thread stays for history but the
  // server rejects new messages ("unfriending closes the channel"), so the
  // client shows a read-only notice instead of the composer
  peerIsFriend: z.boolean(),
  createdAt: z.iso.datetime(),
})

export const ListDmMessagesQuerySchema = z.object({
  ...pageQueryShape,
  since: z.iso.datetime().optional(),
})

export type DmMessage = z.infer<typeof DmMessageSchema>
export type DmPeer = z.infer<typeof DmPeerSchema>
export type DmConversation = z.infer<typeof DmConversationSchema>
