import { apiRequest } from '@/shared/api/httpClient';

export interface DirectContact {
  readonly conversationKey: string;
  readonly userId: string;
  readonly name: string;
  readonly role: string | null;
  readonly studentId: string | null;
  readonly studentName: string | null;
}

export interface DirectConversation {
  readonly conversationKey: string;
  readonly userId: string;
  readonly name: string;
  readonly studentId: string | null;
  readonly studentName: string | null;
  readonly lastMessage: string;
  readonly lastAt: string | null;
  readonly unread: number;
}

export interface DirectThreadMessage {
  readonly id: string;
  readonly body: string;
  readonly senderId: string;
  readonly mine: boolean;
  readonly createdAt: string;
}

export interface DirectThread {
  readonly other: {
    readonly userId: string;
    readonly name: string;
    readonly studentId: string | null;
    readonly studentName: string | null;
  } | null;
  readonly rows: DirectThreadMessage[];
}

export function getDirectContacts(): Promise<{ rows: DirectContact[] }> {
  return apiRequest<{ rows: DirectContact[] }>('/direct_messages/contacts');
}

export function getDirectConversations(): Promise<{ rows: DirectConversation[] }> {
  return apiRequest<{ rows: DirectConversation[] }>('/direct_messages/conversations');
}

export function getDirectThread(
  otherUserId: string,
  studentId?: string | null,
): Promise<DirectThread> {
  const qs = studentId
    ? `?${new URLSearchParams({ studentId }).toString()}`
    : '';
  return apiRequest<DirectThread>(`/direct_messages/thread/${otherUserId}${qs}`);
}

export function sendDirectMessage(
  recipientId: string,
  body: string,
  studentId?: string,
): Promise<DirectThreadMessage> {
  return apiRequest<DirectThreadMessage>('/direct_messages/send', {
    method: 'POST',
    body: { data: { recipientId, body, studentId } },
  });
}
