import { apiRequest } from "@/shared/api/request";
import { API_ENDPOINTS, API_OPERATIONS, apiEndpointPath } from "@/shared/api/generated/endpoints";
import type { AdminUserDto, ApiPage, EntityId, PageQuery, TeamDto, TeamPayload } from "@/shared/api/types";

export const OPERATION_TEAM_ID = 2;

export async function listTeams(query?: Pick<PageQuery, "keyword">): Promise<TeamDto[]> {
  const data = await apiRequest<TeamDto[] | { items?: TeamDto[] }>(apiEndpointPath(API_OPERATIONS.listTeams), { query });
  return Array.isArray(data) ? data : Array.isArray(data?.items) ? data.items : [];
}

export function createTeam(payload: TeamPayload): Promise<TeamDto> {
  const endpoint = API_ENDPOINTS.createTeam;
  return apiRequest<TeamDto, TeamPayload>(apiEndpointPath(API_OPERATIONS.createTeam), {
    body: payload,
    method: endpoint.method
  });
}

export function updateTeam(id: EntityId, payload: TeamPayload): Promise<TeamDto> {
  const endpoint = API_ENDPOINTS.updateTeam;
  return apiRequest<TeamDto, TeamPayload>(apiEndpointPath(API_OPERATIONS.updateTeam, { team_id: id }), {
    body: payload,
    method: endpoint.method
  });
}

export function listTeamUsers(teamId: EntityId, query?: Pick<PageQuery, "keyword" | "status">): Promise<ApiPage<AdminUserDto>> {
  return apiRequest<ApiPage<AdminUserDto>>(apiEndpointPath(API_OPERATIONS.listTeamUsers, { team_id: teamId }), { query });
}

export function listOperationUsers(query?: Pick<PageQuery, "keyword" | "status">): Promise<ApiPage<AdminUserDto>> {
  return listTeamUsers(OPERATION_TEAM_ID, query);
}
