/**
 * Contact folder API client — CRUD, move contacts, reorder.
 */

import { apiGet, apiPost, apiPut, apiDelete } from './client';

export interface ContactFolder {
  id: string;
  name: string;
  parent_id: string | null;
  user_id: string;
  sort_order: number;
  contact_count: number;
}

export interface ContactFolderTreeNode extends ContactFolder {
  children: ContactFolderTreeNode[];
}

// ── Folders ──

export const fetchContactFolders = () =>
  apiGet<ContactFolder[]>('/contact-folders');

export const createContactFolder = (data: { name: string; parent_id?: string }) =>
  apiPost<ContactFolder>('/contact-folders', data);

export const updateContactFolder = (id: string, data: Partial<ContactFolder>) =>
  apiPut<ContactFolder>(`/contact-folders/${id}`, data);

export const deleteContactFolder = (id: string) =>
  apiDelete(`/contact-folders/${id}`);

export const reorderContactFolders = (folderId: string, orders: { id: string; sort_order: number; parent_id?: string | null }[]) =>
  apiPut(`/contact-folders/${folderId}/reorder`, orders);

// ── Move contact ──

export const moveContactToFolder = (contactId: string, folderId: string | null) =>
  apiPut<{ id: string; folder_id: string | null }>(`/contact-folders/contacts/${contactId}/move`, { folder_id: folderId });

// ── Tree builder ──

export function buildFolderTree(folders: ContactFolder[]): ContactFolderTreeNode[] {
  const folderMap = new Map<string, ContactFolderTreeNode>();
  const roots: ContactFolderTreeNode[] = [];

  for (const f of folders) {
    folderMap.set(f.id, { ...f, children: [] });
  }

  for (const f of folders) {
    const node = folderMap.get(f.id)!;
    if (f.parent_id && folderMap.has(f.parent_id)) {
      folderMap.get(f.parent_id)!.children.push(node);
    } else {
      roots.push(node);
    }
  }

  return roots;
}
