import { RequestClient } from '@vben/request';
import { useAccessStore } from '@vben/stores';

const imRequestClient = new RequestClient({
  baseURL: 'http://localhost:5212/api',
});

imRequestClient.addRequestInterceptor({
  fulfilled: async (config) => {
    const accessStore = useAccessStore();
    if (accessStore.accessToken) {
      config.headers.Authorization = `Bearer ${accessStore.accessToken}`;
    }
    return config;
  },
});

imRequestClient.addResponseInterceptor({
  fulfilled: (response) => {
    const data = response.data as any;
    if (data?.code === 0) {
      response.data = data.data;
    }
    return response;
  },
});

export namespace ImApi {
  export interface Conversation {
    id: string;
    type: number;
    lastMessageContent: string | null;
    lastMessageAt: string | null;
    unreadCount: number;
    groupName: string | null;
    groupAvatar: string | null;
    otherUserId: string | null;
    otherUserName: string | null;
    otherUserAvatar: string | null;
  }

  export interface Message {
    id: string;
    conversationId: string;
    senderId: string;
    senderName: string;
    senderAvatar: string | null;
    contentType: number;
    content: string;
    metadata: MessageMetadata | null;
    replyToId: string | null;
    createdAt: string;
  }

  export interface MessageMetadata {
    fileName?: string | null;
    fileSize?: number | null;
    fileUrl?: string | null;
    imageUrl?: string | null;
    imageWidth?: number | null;
    imageHeight?: number | null;
    emojiCode?: string | null;
  }

  export interface MessageHistory {
    messages: Message[];
    hasMore: boolean;
  }

  export interface UnreadCounts {
    items: { conversationId: string; unreadCount: number }[];
    total: number;
  }

  export interface GroupInfo {
    id: string;
    conversationId: string;
    name: string;
    avatar: string | null;
    description: string | null;
    ownerId: string;
    memberCount: number;
    createdAt: string;
  }

  export interface GroupMember {
    userId: string;
    userName: string;
    avatar: string | null;
    role: number;
    joinedAt: string;
  }
}

export async function getConversationsApi() {
  return imRequestClient.get<ImApi.Conversation[]>('/conversations');
}

export async function getMessageHistoryApi(
  conversationId: string,
  beforeId?: string,
  limit: number = 50,
) {
  const params: Record<string, any> = { limit };
  if (beforeId) params.beforeId = beforeId;
  return imRequestClient.get<ImApi.MessageHistory>(
    `/conversations/${conversationId}/messages`,
    { params },
  );
}

export async function getUnreadCountApi() {
  return imRequestClient.get<ImApi.UnreadCounts>('/unread');
}

export async function createGroupApi(data: {
  name: string;
  avatar?: string;
  description?: string;
  memberUserIds: string[];
}) {
  return imRequestClient.post<ImApi.GroupInfo>('/groups', data);
}

export async function updateGroupApi(
  groupId: string,
  data: { name?: string; avatar?: string; description?: string },
) {
  return imRequestClient.put<ImApi.GroupInfo>(`/groups/${groupId}`, data);
}

export async function deleteGroupApi(groupId: string) {
  return imRequestClient.delete(`/groups/${groupId}`);
}

export async function addGroupMemberApi(groupId: string, userIds: string[]) {
  return imRequestClient.post(`/groups/${groupId}/members`, { userIds });
}

export async function removeGroupMemberApi(groupId: string, userId: string) {
  return imRequestClient.delete(`/groups/${groupId}/members/${userId}`);
}

export async function getGroupMembersApi(groupId: string) {
  return imRequestClient.get<ImApi.GroupMember[]>(`/groups/${groupId}/members`);
}
