/**
 * Tags plugin API client.
 *
 * All requests use the shared `apiClient` (`baseURL: '/api/v1'`) and target
 * the Tags plugin routes under `/tags/...`.
 */

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

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

export type EntityType = 'contact' | 'file' | 'calendar_entry';

export interface Tag {
  id: string;
  name: string;
  color: string;
  description?: string | null;
  created_by: string;
  created_at?: string | null;
  updated_at?: string | null;
  usage_count?: number;
}

export interface TagAssignment {
  id: string;
  tag_id: string;
  entity_type: EntityType;
  entity_id: string;
  tag?: Tag;
  created_at?: string | null;
}

export interface TagEntity {
  entity_type: EntityType;
  entity_id: string;
  entity_name: string;
}

// ─── Payloads ──────────────────────────────────────────────────────────────

export interface CreateTagPayload {
  name: string;
  color?: string;
  description?: string | null;
}

export interface UpdateTagPayload {
  name?: string;
  color?: string;
  description?: string | null;
}

export interface AssignTagPayload {
  tag_id: string;
  entity_type: EntityType;
  entity_id: string;
}

export interface UnassignTagPayload {
  tag_id: string;
  entity_type: EntityType;
  entity_id: string;
}

export interface BulkAssignPayload {
  tag_ids: string[];
  entity_type: EntityType;
  entity_ids: string[];
}

// ─── Tags CRUD ─────────────────────────────────────────────────────────────

export function fetchTags(): Promise<Tag[]> {
  return apiGet<Tag[]>('/tags');
}

export function createTag(payload: CreateTagPayload): Promise<Tag> {
  return apiPost<Tag>('/tags', payload);
}

export function updateTag(tagId: string, payload: UpdateTagPayload): Promise<Tag> {
  return apiPatch<Tag>(`/tags/${tagId}`, payload);
}

export function deleteTag(tagId: string): Promise<void> {
  return apiDelete<void>(`/tags/${tagId}`);
}

// ─── Tag Assignments ───────────────────────────────────────────────────────

export function assignTag(payload: AssignTagPayload): Promise<TagAssignment> {
  return apiPost<TagAssignment>('/tags/assign', payload);
}

export function unassignTag(payload: UnassignTagPayload): Promise<void> {
  return apiDelete<void>('/tags/assign', { data: payload });
}

export function bulkAssignTags(payload: BulkAssignPayload): Promise<void> {
  return apiPost<void>('/tags/bulk-assign', payload);
}

export function fetchTagEntities(tagId: string): Promise<TagEntity[]> {
  return apiGet<TagEntity[]>(`/tags/${tagId}/entities`);
}
