import { apiClient } from "./client";

export interface TeamMember {
  userId: number;
  username: string;
  email: string;
  avatarUrl?: string;
  status: number;
  role: string;
  position?: string;
  joinedAt: string;
}

export interface TeamGroup {
  id: number;
  name: string;
  description?: string;
  memberIds: number[];
  createdAt: string;
}

export interface CreateMemberPayload {
  username: string;
  email: string;
  password: string;
  role?: string;
  position?: string;
}

export const teamApi = {
  listMembers: async (): Promise<TeamMember[]> => {
    const r = await apiClient.get("/team/members");
    return r.data.data ?? [];
  },
  addMember: async (payload: CreateMemberPayload): Promise<TeamMember> => {
    const r = await apiClient.post("/team/members", payload);
    return r.data.data;
  },
  updateMember: async (userId: number, patch: { role?: string; position?: string }): Promise<TeamMember> => {
    const r = await apiClient.put(`/team/members/${userId}`, patch);
    return r.data.data;
  },
  removeMember: async (userId: number): Promise<void> => {
    await apiClient.delete(`/team/members/${userId}`);
  },

  listGroups: async (): Promise<TeamGroup[]> => {
    const r = await apiClient.get("/team/groups");
    return r.data.data ?? [];
  },
  createGroup: async (payload: { name: string; description?: string }): Promise<TeamGroup> => {
    const r = await apiClient.post("/team/groups", payload);
    return r.data.data;
  },
  updateGroup: async (groupId: number, patch: { name?: string; description?: string }): Promise<TeamGroup> => {
    const r = await apiClient.put(`/team/groups/${groupId}`, patch);
    return r.data.data;
  },
  deleteGroup: async (groupId: number): Promise<void> => {
    await apiClient.delete(`/team/groups/${groupId}`);
  },
  addGroupMember: async (groupId: number, userId: number): Promise<void> => {
    await apiClient.post(`/team/groups/${groupId}/members/${userId}`);
  },
  removeGroupMember: async (groupId: number, userId: number): Promise<void> => {
    await apiClient.delete(`/team/groups/${groupId}/members/${userId}`);
  },
};
