import type { User, Session, Drawing, DrawingRevision, Team, TeamMembership, TeamInvite, Template, Folder, ActivityEvent } from '@/types';

const API_BASE = '/api';

class ApiError extends Error {
  constructor(public status: number, message: string) {
    super(message);
  }
}

async function fetchApi<T>(path: string, options?: RequestInit): Promise<T> {
  const headers: Record<string, string> = {};
  if (options?.body) {
    headers['Content-Type'] = 'application/json';
  }
  const res = await fetch(`${API_BASE}${path}`, {
    ...options,
    credentials: 'include',
    headers: {
      ...headers,
      ...options?.headers,
    },
  });
  if (!res.ok) throw new ApiError(res.status, await res.text());
  return res.json();
}

export const api = {
  auth: {
    me: (): Promise<User> => fetchApi('/auth/me'),
    setupStatus: (): Promise<{ has_users: boolean }> => fetchApi('/auth/setup-status'),
    login: (email: string, password: string): Promise<{ user: User; session: Session }> =>
      fetchApi('/auth/login', { method: 'POST', body: JSON.stringify({ email, password }) }),
    signup: (name: string, email: string, password: string): Promise<{ user: User; session: Session }> =>
      fetchApi('/auth/signup', { method: 'POST', body: JSON.stringify({ name, email, password }) }),
    logout: (): Promise<void> => fetchApi('/auth/logout', { method: 'POST' }),
  },
  drawings: {
    list: (teamId?: string): Promise<Drawing[]> =>
      fetchApi(`/drawings${teamId ? `?team_id=${teamId}` : ''}`),
    get: (id: string): Promise<Drawing> => fetchApi(`/drawings/${id}`),
    create: (data: object): Promise<Drawing> =>
      fetchApi('/drawings', { method: 'POST', body: JSON.stringify(data) }),
    update: (id: string, data: object): Promise<Drawing> =>
      fetchApi(`/drawings/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
    delete: (id: string): Promise<{ ok: boolean }> =>
      fetchApi(`/drawings/${id}`, { method: 'DELETE' }),
    autosave: (id: string, snapshot: object): Promise<{ ok: boolean }> =>
      fetchApi(`/drawings/${id}/autosave`, { method: 'PATCH', body: JSON.stringify({ snapshot }) }),
  },
  revisions: {
    list: (drawingId: string): Promise<DrawingRevision[]> =>
      fetchApi(`/drawings/${drawingId}/revisions`),
    create: (drawingId: string, snapshot: object, changeSummary?: string): Promise<DrawingRevision> =>
      fetchApi(`/drawings/${drawingId}/revisions`, {
        method: 'POST',
        body: JSON.stringify({ snapshot, change_summary: changeSummary }),
      }),
  },
  folders: {
    list: (): Promise<Folder[]> => fetchApi('/folders'),
    create: (data: object): Promise<Folder> =>
      fetchApi('/folders', { method: 'POST', body: JSON.stringify(data) }),
    update: (id: string, data: object): Promise<Folder> =>
      fetchApi(`/folders/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
    delete: (id: string): Promise<void> =>
      fetchApi(`/folders/${id}`, { method: 'DELETE' }),
    reorder: (folderIds: string[]): Promise<Folder[]> =>
      fetchApi('/folders/reorder', { method: 'POST', body: JSON.stringify({ folder_ids: folderIds }) }),
  },
  teams: {
    list: (): Promise<Team[]> => fetchApi('/teams'),
    create: (data: { name: string; slug: string }): Promise<Team> => fetchApi('/teams', { method: 'POST', body: JSON.stringify(data) }),
    members: (teamId: string): Promise<TeamMembership[]> => fetchApi(`/teams/${teamId}/members`),
    invites: (teamId: string): Promise<TeamInvite[]> => fetchApi(`/teams/${teamId}/invites`),
    createInvite: (teamId: string, data: { email: string; role: string }): Promise<TeamInvite> => fetchApi(`/teams/${teamId}/invites`, { method: 'POST', body: JSON.stringify(data) }),
    acceptInvite: (token: string): Promise<void> => fetchApi('/invites/accept', { method: 'POST', body: JSON.stringify({ token }) }),
    createUser: (teamId: string, data: { name: string; email: string; password: string; role: string }): Promise<User> => fetchApi(`/teams/${teamId}/users`, { method: 'POST', body: JSON.stringify(data) }),
  },
  templates: {
    list: (): Promise<Template[]> => fetchApi('/templates'),
    create: (data: { name: string; description?: string; team_id?: string; snapshot: object; metadata?: Record<string, unknown> }): Promise<Template> =>
      fetchApi('/templates', { method: 'POST', body: JSON.stringify(data) }),
    delete: (id: string): Promise<{ ok: boolean }> =>
      fetchApi(`/templates/${id}`, { method: 'DELETE' }),
  },
  stats: {
    get: (teamId?: string): Promise<{
      teams: number;
      members: number;
      projects: number;
      folders: number;
      drawings: number;
      templates: number;
      revisions: number;
      assets: number;
      storage_bytes: number;
    }> => fetchApi(`/stats${teamId ? `?team_id=${teamId}` : ''}`),
  },
  activity: {
    list: (): Promise<ActivityEvent[]> => fetchApi('/activity'),
  },
  search: {
    get: (q: string): Promise<Drawing[]> => fetchApi(`/search?q=${encodeURIComponent(q)}`),
  },
  notifications: {
    list: (): Promise<Notification[]> => fetchApi('/notifications'),
    markRead: (id: string): Promise<{ ok: boolean }> => fetchApi(`/notifications/${id}/read`, { method: 'POST' }),
    markAllRead: (): Promise<{ ok: boolean }> => fetchApi('/notifications/read-all', { method: 'POST' }),
  },
};
