import {
  acceptInvite as acceptInviteRequest,
  connectMailbox as connectMailboxRequest,
  createBoardGroup as createBoardGroupRequest,
  createCalendarEvent,
  createClient,
  createFocusSession as createFocusSessionRequest,
  createInvite as createInviteRequest,
  createLabel as createLabelRequest,
  createNote as createNoteRequest,
  createOutgoingMail as createOutgoingMailRequest,
  createTask as createTaskRequest,
  createTaskFromMail as createTaskFromMailRequest,
  deleteTaskAttachment as deleteTaskAttachmentRequest,
  getInviteByToken as getInviteByTokenRequest,
  listActivity,
  listBoardGroups,
  listCalendarEvents,
  listFocusSessions,
  listInvites,
  listLabels,
  listMailMessages as listMailMessagesRequest,
  listMailboxes as listMailboxesRequest,
  listMembers,
  listNotes,
  listOutgoingMails as listOutgoingMailsRequest,
  listTasks,
  listWorkspaces,
  revokeInvite as revokeInviteRequest,
  syncMailbox as syncMailboxRequest,
  uploadTaskAttachment as uploadTaskAttachmentRequest,
  updateBoardGroup as updateBoardGroupRequest,
  updateCalendarEvent,
  updateFocusSession as updateFocusSessionRequest,
  updateMember as updateMemberRequest,
  updateNote as updateNoteRequest,
  updateTask as updateTaskRequest
} from "@productier/api-client";

const API_BASE_URL = import.meta.env.VITE_API_URL || "http://localhost:48080";

const apiClient = createClient({
  baseUrl: API_BASE_URL
});

// Helper for custom API routes not in the generated client
export async function apiFetch(path: string, init?: RequestInit): Promise<Response> {
  const res = await fetch(`${API_BASE_URL}${path}`, {
    ...init,
    headers: {
      ...init?.headers
    }
  });
  if (!res.ok) {
    throw new Error(`API error: ${res.status} ${res.statusText}`);
  }
  return res;
}

export async function fetchWorkspaceBundle(workspaceSlug: string) {
  const [workspaces, members, invites, boardGroups, labels, tasks, events, notes, focusSessions, activity] = await Promise.all([
    listWorkspaces({ client: apiClient, responseStyle: "data" }),
    listMembers({ client: apiClient, responseStyle: "data", query: { workspaceSlug } }),
    listInvites({ client: apiClient, responseStyle: "data", query: { workspaceSlug } }),
    listBoardGroups({ client: apiClient, responseStyle: "data", query: { workspaceSlug } }),
    listLabels({ client: apiClient, responseStyle: "data", query: { workspaceSlug } }),
    listTasks({ client: apiClient, responseStyle: "data", query: { workspaceSlug } }),
    listCalendarEvents({ client: apiClient, responseStyle: "data", query: { workspaceSlug } }),
    listNotes({ client: apiClient, responseStyle: "data", query: { workspaceSlug } }),
    listFocusSessions({ client: apiClient, responseStyle: "data", query: { workspaceSlug } }),
    listActivity({ client: apiClient, responseStyle: "data", query: { workspaceSlug, limit: 40 } })
  ]);

  return {
    workspaces: workspaces?.data ?? [],
    members: members?.data ?? [],
    invites: invites?.data ?? [],
    boardGroups: boardGroups?.data ?? [],
    labels: labels?.data ?? [],
    tasks: tasks?.data ?? [],
    events: events?.data ?? [],
    notes: notes?.data ?? [],
    focusSessions: focusSessions?.data ?? [],
    activities: activity?.data ?? []
  };
}

export async function apiGetInviteByToken(token: string) {
  const response = await getInviteByTokenRequest({
    client: apiClient,
    responseStyle: "data",
    path: { token }
  });
  return response?.data;
}

export async function apiCreateInvite(body: Parameters<typeof createInviteRequest>[0]["body"]) {
  const response = await createInviteRequest({ client: apiClient, responseStyle: "data", body });
  return response?.data;
}

export async function apiRevokeInvite(inviteId: string) {
  await revokeInviteRequest({
    client: apiClient,
    responseStyle: "data",
    path: { inviteId }
  });
}

export async function apiAcceptInvite(token: string, body: Parameters<typeof acceptInviteRequest>[0]["body"]) {
  const response = await acceptInviteRequest({
    client: apiClient,
    responseStyle: "data",
    path: { token },
    body
  });
  return response?.data;
}

export async function apiCreateTask(body: Parameters<typeof createTaskRequest>[0]["body"]) {
  const response = await createTaskRequest({ client: apiClient, responseStyle: "data", body });
  return response?.data;
}

export async function apiUpdateTask(taskId: string, body: Parameters<typeof updateTaskRequest>[0]["body"]) {
  const response = await updateTaskRequest({
    client: apiClient,
    responseStyle: "data",
    path: { taskId },
    body
  });
  return response?.data;
}

export async function apiUpdateMember(memberId: string, body: Parameters<typeof updateMemberRequest>[0]["body"]) {
  const response = await updateMemberRequest({
    client: apiClient,
    responseStyle: "data",
    path: { memberId },
    body
  });
  return response?.data;
}

export async function apiCreateEvent(body: Parameters<typeof createCalendarEvent>[0]["body"]) {
  const response = await createCalendarEvent({ client: apiClient, responseStyle: "data", body });
  return response?.data;
}

export async function apiUpdateEvent(eventId: string, body: Parameters<typeof updateCalendarEvent>[0]["body"]) {
  const response = await updateCalendarEvent({
    client: apiClient,
    responseStyle: "data",
    path: { eventId },
    body
  });
  return response?.data;
}

export async function apiCreateNote(body: Parameters<typeof createNoteRequest>[0]["body"]) {
  const response = await createNoteRequest({ client: apiClient, responseStyle: "data", body });
  return response?.data;
}

export async function apiUpdateNote(noteId: string, body: Parameters<typeof updateNoteRequest>[0]["body"]) {
  const response = await updateNoteRequest({
    client: apiClient,
    responseStyle: "data",
    path: { noteId },
    body
  });
  return response?.data;
}

export async function apiCreateBoardGroup(body: Parameters<typeof createBoardGroupRequest>[0]["body"]) {
  const response = await createBoardGroupRequest({ client: apiClient, responseStyle: "data", body });
  return response?.data;
}

export async function apiUpdateBoardGroup(groupId: string, body: Parameters<typeof updateBoardGroupRequest>[0]["body"]) {
  const response = await updateBoardGroupRequest({
    client: apiClient,
    responseStyle: "data",
    path: { groupId },
    body
  });
  return response?.data;
}

export async function apiUploadTaskAttachment(taskId: string, file: File) {
  const formData = new FormData();
  formData.set("file", file);
  const response = await uploadTaskAttachmentRequest({
    client: apiClient,
    responseStyle: "data",
    path: { taskId },
    body: formData
  });
  return response?.data;
}

export async function apiDeleteTaskAttachment(taskId: string, attachmentId: string) {
  await deleteTaskAttachmentRequest({
    client: apiClient,
    responseStyle: "data",
    path: { taskId, attachmentId }
  });
}

export async function apiCreateLabel(body: Parameters<typeof createLabelRequest>[0]["body"]) {
  const response = await createLabelRequest({ client: apiClient, responseStyle: "data", body });
  return response?.data;
}

export async function apiCreateFocusSession(body: Parameters<typeof createFocusSessionRequest>[0]["body"]) {
  const response = await createFocusSessionRequest({ client: apiClient, responseStyle: "data", body });
  return response?.data;
}

export async function apiUpdateFocusSession(sessionId: string, body: Parameters<typeof updateFocusSessionRequest>[0]["body"]) {
  const response = await updateFocusSessionRequest({
    client: apiClient,
    responseStyle: "data",
    path: { sessionId },
    body
  });
  return response?.data;
}

export async function apiListMailboxes(workspaceSlug: string) {
  const response = await listMailboxesRequest({
    client: apiClient,
    responseStyle: "data",
    query: { workspaceSlug }
  });
  return response?.data ?? [];
}

export async function apiConnectMailbox(body: Parameters<typeof connectMailboxRequest>[0]["body"]) {
  const response = await connectMailboxRequest({ client: apiClient, responseStyle: "data", body });
  return response?.data;
}

export async function apiSyncMailbox(mailboxId: string) {
  const response = await syncMailboxRequest({
    client: apiClient,
    responseStyle: "data",
    path: { mailboxId }
  });
  return response?.data;
}

export async function apiListMailMessages(workspaceSlug: string, mailboxId?: string) {
  const response = await listMailMessagesRequest({
    client: apiClient,
    responseStyle: "data",
    query: {
      workspaceSlug,
      ...(mailboxId ? { mailboxId } : {})
    }
  });
  return response?.data ?? [];
}

export async function apiListOutgoingMails(workspaceSlug: string, mailboxId?: string) {
  const response = await listOutgoingMailsRequest({
    client: apiClient,
    responseStyle: "data",
    query: {
      workspaceSlug,
      ...(mailboxId ? { mailboxId } : {})
    }
  });
  return response?.data ?? [];
}

export async function apiCreateOutgoingMail(body: Parameters<typeof createOutgoingMailRequest>[0]["body"]) {
  const response = await createOutgoingMailRequest({
    client: apiClient,
    responseStyle: "data",
    body
  });
  return response?.data;
}

export async function apiCreateTaskFromMail(messageId: string, body: Parameters<typeof createTaskFromMailRequest>[0]["body"]) {
  const response = await createTaskFromMailRequest({
    client: apiClient,
    responseStyle: "data",
    path: { messageId },
    body
  });
  return response?.data;
}
