/**
 * Workspaces API Client
 * User-scoped workspace discovery — does NOT require X-Workspace-Id header.
 */

import type { WorkspaceMemberRole } from "@mosaic/shared";
import { apiDelete, apiGet, apiPatch, apiPost } from "./client";

export interface UserWorkspace {
  id: string;
  name: string;
  ownerId: string;
  role: WorkspaceMemberRole;
  createdAt: string;
}

export interface CreateWorkspaceDto {
  name: string;
}

export interface CreatedWorkspace {
  id: string;
  name: string;
  ownerId: string;
  settings: Record<string, unknown>;
  createdAt: string;
  updatedAt: string;
  memberCount: number;
}

export interface WorkspaceMemberUser {
  id: string;
  email: string;
  name: string | null;
  image: string | null;
}

export interface WorkspaceMemberEntry {
  workspaceId: string;
  userId: string;
  role: WorkspaceMemberRole;
  joinedAt: string;
  user: WorkspaceMemberUser;
}

export interface AddMemberDto {
  userId: string;
  role: WorkspaceMemberRole;
}

export interface UpdateMemberRoleDto {
  role: WorkspaceMemberRole;
}

export async function fetchUserWorkspaces(): Promise<UserWorkspace[]> {
  return apiGet<UserWorkspace[]>("/api/workspaces");
}

export async function createWorkspace(dto: CreateWorkspaceDto): Promise<CreatedWorkspace> {
  return apiPost<CreatedWorkspace>("/api/admin/workspaces", dto);
}

export async function fetchWorkspaceMembers(workspaceId: string): Promise<WorkspaceMemberEntry[]> {
  return apiGet<WorkspaceMemberEntry[]>(`/api/workspaces/${workspaceId}/members`);
}

export async function addWorkspaceMember(
  workspaceId: string,
  dto: AddMemberDto
): Promise<WorkspaceMemberEntry> {
  return apiPost<WorkspaceMemberEntry>(`/api/workspaces/${workspaceId}/members`, dto);
}

export async function updateWorkspaceMemberRole(
  workspaceId: string,
  userId: string,
  dto: UpdateMemberRoleDto
): Promise<WorkspaceMemberEntry> {
  return apiPatch<WorkspaceMemberEntry>(`/api/workspaces/${workspaceId}/members/${userId}`, dto);
}

export async function removeWorkspaceMember(workspaceId: string, userId: string): Promise<void> {
  await apiDelete<unknown>(`/api/workspaces/${workspaceId}/members/${userId}`);
}
