/**
 * Organization API client.
 *
 * ⚠️ AUTO-GENERATED BY PRISM - DO NOT EDIT
 */

const API_BASE = '/api/v1/organizations';

function getHeaders(): HeadersInit {
  return {
    'Content-Type': 'application/json',
  };
}

async function handleResponse<T>(response: Response): Promise<T> {
  if (!response.ok) {
    const error = await response.json().catch(() => ({ detail: response.statusText }));
    throw new Error(error.detail || `HTTP ${response.status}`);
  }
  if (response.status === 204) return undefined as T;
  return response.json();
}

// ── Types ───────────────────────────────────────────────────────

export interface Organization {
  id: number;
  name: string;
  {{ slug_field }}: string;
  description: string | null;
  avatar_url: string | null;
  is_active: boolean;
  created_at: string;
  updated_at: string;
  member_count: number | null;
  current_user_role: string | null;
}

export interface OrganizationListResponse {
  organizations: Organization[];
  total: number;
  skip: number;
  limit: number;
}

export interface Member {
  id: number;
  user_id: number;
  {{ username_field }}: string | null;
  role: string;
  is_active: boolean;
  joined_at: string;
}

export interface MemberListResponse {
  members: Member[];
  total: number;
  skip: number;
  limit: number;
}

export interface Invitation {
  id: number;
  email: string;
  role: string;
  created_at: string;
  expires_at: string;
}

export interface OrgRole {
  name: string;
  permissions: string[];
  description: string;
}

// ── Organization CRUD ───────────────────────────────────────────

export async function createOrganization(data: {
  name: string;
  slug?: string;
  description?: string;
}): Promise<Organization> {
  const res = await fetch(API_BASE + '/', {
    method: 'POST',
    headers: getHeaders(),
    credentials: 'include',
    body: JSON.stringify(data),
  });
  return handleResponse<Organization>(res);
}

export async function listMyOrganizations(
  skip = 0,
  limit = 50,
): Promise<OrganizationListResponse> {
  const res = await fetch(
    `${API_BASE}/?skip=${skip}&limit=${limit}`,
    { credentials: 'include' },
  );
  return handleResponse<OrganizationListResponse>(res);
}

export async function getOrganization(slug: string): Promise<Organization> {
  const res = await fetch(`${API_BASE}/${slug}`, { credentials: 'include' });
  return handleResponse<Organization>(res);
}

export async function updateOrganization(
  slug: string,
  data: { name?: string; description?: string; avatar_url?: string },
): Promise<Organization> {
  const res = await fetch(`${API_BASE}/${slug}`, {
    method: 'PATCH',
    headers: getHeaders(),
    credentials: 'include',
    body: JSON.stringify(data),
  });
  return handleResponse<Organization>(res);
}

export async function deleteOrganization(slug: string): Promise<void> {
  const res = await fetch(`${API_BASE}/${slug}`, {
    method: 'DELETE',
    credentials: 'include',
  });
  return handleResponse<void>(res);
}

// ── Members ─────────────────────────────────────────────────────

export async function listMembers(
  slug: string,
  skip = 0,
  limit = 50,
): Promise<MemberListResponse> {
  const res = await fetch(
    `${API_BASE}/${slug}/members?skip=${skip}&limit=${limit}`,
    { credentials: 'include' },
  );
  return handleResponse<MemberListResponse>(res);
}

export async function addMember(
  slug: string,
  data: { user_id: number; role?: string },
): Promise<Member> {
  const res = await fetch(`${API_BASE}/${slug}/members`, {
    method: 'POST',
    headers: getHeaders(),
    credentials: 'include',
    body: JSON.stringify(data),
  });
  return handleResponse<Member>(res);
}

export async function updateMemberRole(
  slug: string,
  userId: number,
  role: string,
): Promise<Member> {
  const res = await fetch(`${API_BASE}/${slug}/members/${userId}`, {
    method: 'PATCH',
    headers: getHeaders(),
    credentials: 'include',
    body: JSON.stringify({ role }),
  });
  return handleResponse<Member>(res);
}

export async function removeMember(
  slug: string,
  userId: number,
): Promise<void> {
  const res = await fetch(`${API_BASE}/${slug}/members/${userId}`, {
    method: 'DELETE',
    credentials: 'include',
  });
  return handleResponse<void>(res);
}

export async function leaveOrganization(slug: string): Promise<void> {
  const res = await fetch(`${API_BASE}/${slug}/leave`, {
    method: 'POST',
    credentials: 'include',
  });
  return handleResponse<void>(res);
}

// ── Invitations ─────────────────────────────────────────────────

export async function inviteMember(
  slug: string,
  data: { email: string; role?: string },
): Promise<Invitation> {
  const res = await fetch(`${API_BASE}/${slug}/invitations`, {
    method: 'POST',
    headers: getHeaders(),
    credentials: 'include',
    body: JSON.stringify(data),
  });
  return handleResponse<Invitation>(res);
}

export async function listInvitations(slug: string): Promise<Invitation[]> {
  const res = await fetch(`${API_BASE}/${slug}/invitations`, {
    credentials: 'include',
  });
  return handleResponse<Invitation[]>(res);
}

export async function revokeInvitation(
  slug: string,
  invitationId: number,
): Promise<void> {
  const res = await fetch(`${API_BASE}/${slug}/invitations/${invitationId}`, {
    method: 'DELETE',
    credentials: 'include',
  });
  return handleResponse<void>(res);
}

export async function acceptInvitation(token: string): Promise<Member> {
  const res = await fetch(`${API_BASE}/invitations/accept`, {
    method: 'POST',
    headers: getHeaders(),
    credentials: 'include',
    body: JSON.stringify({ token }),
  });
  return handleResponse<Member>(res);
}

// ── Roles ───────────────────────────────────────────────────────

export async function listOrgRoles(): Promise<OrgRole[]> {
  const res = await fetch(`${API_BASE}/roles`, { credentials: 'include' });
  return handleResponse<OrgRole[]>(res);
}
