import { clientMetaSystemAdapter } from "@nextsparkjs/registries/entity-registry.client";
function getApiBaseUrl() {
  if (typeof window !== "undefined") {
    return window.location.origin;
  } else {
    return process.env.NEXT_PUBLIC_APP_URL || "http://localhost:5173";
  }
}
function getCurrentTeamId() {
  if (typeof window !== "undefined") {
    return localStorage.getItem("activeTeamId");
  }
  return null;
}
function buildHeaders(additionalHeaders = {}) {
  const headers = {
    "Content-Type": "application/json",
    ...additionalHeaders
  };
  const teamId = getCurrentTeamId();
  if (teamId) {
    headers["x-team-id"] = teamId;
  }
  return headers;
}
class EntityApiClient {
  baseUrl;
  constructor(baseUrl = "/api/v1") {
    this.baseUrl = baseUrl;
  }
  /**
   * Get endpoint path from entity configuration using slug
   * This ensures consistent URLs across routes, endpoints, and navigation
   */
  async getEndpointPath(entityType) {
    try {
      const apiPath = clientMetaSystemAdapter.getApiPath(entityType);
      if (apiPath) {
        return apiPath;
      }
      try {
        const entities = clientMetaSystemAdapter.getAllEntityConfigs();
        const entity = entities.find((config) => config.name === entityType);
        if (entity == null ? void 0 : entity.apiPath) {
          return entity.apiPath;
        }
      } catch (registryError) {
        console.warn(`Registry fallback failed for '${entityType}':`, registryError);
      }
      const fallback = entityType.endsWith("s") ? entityType : `${entityType}s`;
      console.warn(`Using fallback endpoint for '${entityType}': ${fallback}`);
      return fallback;
    } catch (error) {
      console.error(`Error loading entity config for '${entityType}':`, error);
      const fallback = entityType.endsWith("s") ? entityType : `${entityType}s`;
      return fallback;
    }
  }
  /**
   * Get list of entities
   */
  async list(entityType, params = {}) {
    const endpointPath = await this.getEndpointPath(entityType);
    const url = new URL(`${this.baseUrl}/${endpointPath}`, getApiBaseUrl());
    if (params.page) url.searchParams.set("page", params.page.toString());
    if (params.limit) url.searchParams.set("limit", params.limit.toString());
    if (params.userId) url.searchParams.set("userId", params.userId);
    if (params.includeMeta) url.searchParams.set("includeMeta", "true");
    if (params.filters) {
      Object.entries(params.filters).forEach(([key, value]) => {
        url.searchParams.set(key, value);
      });
    }
    const response = await fetch(url.toString(), {
      method: "GET",
      headers: buildHeaders(),
      credentials: "include"
      // Include cookies for session auth
    });
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      let userMessage = `Error al cargar ${entityType}`;
      if (response.status === 401) {
        userMessage = "No tienes permisos para acceder a estos datos. Por favor, inicia sesi\xF3n nuevamente.";
      } else if (response.status === 403) {
        userMessage = "No tienes los permisos necesarios para realizar esta acci\xF3n.";
      } else if (response.status === 404) {
        userMessage = "Los datos solicitados no fueron encontrados.";
      } else if (response.status === 400 && errorData.code === "TEAM_CONTEXT_REQUIRED") {
        console.warn("[EntityApiClient] Team context not ready yet, returning empty list");
        return {
          success: true,
          data: [],
          info: {
            timestamp: (/* @__PURE__ */ new Date()).toISOString(),
            page: 1,
            limit: params.limit || 20,
            total: 0,
            totalPages: 0,
            hasNextPage: false,
            hasPrevPage: false
          }
        };
      } else if (response.status >= 500) {
        userMessage = "Error interno del servidor. Por favor, intenta m\xE1s tarde.";
      } else if (errorData.message && !errorData.message.includes("API key")) {
        userMessage = errorData.message;
      }
      throw new Error(userMessage);
    }
    return response.json();
  }
  /**
   * Get single entity by ID
   */
  async get(entityType, id, includeMeta = false) {
    const endpointPath = await this.getEndpointPath(entityType);
    const url = new URL(`${this.baseUrl}/${endpointPath}/${id}`, getApiBaseUrl());
    if (includeMeta) {
      url.searchParams.set("includeMeta", "true");
    }
    const response = await fetch(url.toString(), {
      method: "GET",
      headers: buildHeaders(),
      credentials: "include"
      // Include cookies for session auth
    });
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      let userMessage = `Error al cargar ${entityType}`;
      if (response.status === 401) {
        userMessage = "No tienes permisos para acceder a estos datos. Por favor, inicia sesi\xF3n nuevamente.";
      } else if (response.status === 403) {
        userMessage = "No tienes los permisos necesarios para realizar esta acci\xF3n.";
      } else if (response.status === 404) {
        userMessage = "El elemento solicitado no fue encontrado.";
      } else if (response.status >= 500) {
        userMessage = "Error interno del servidor. Por favor, intenta m\xE1s tarde.";
      } else if (errorData.message && !errorData.message.includes("API key")) {
        userMessage = errorData.message;
      }
      throw new Error(userMessage);
    }
    const result = await response.json();
    return result.data;
  }
  /**
   * Create new entity
   */
  async create(entityType, data) {
    const endpointPath = await this.getEndpointPath(entityType);
    const response = await fetch(`${this.baseUrl}/${endpointPath}`, {
      method: "POST",
      headers: buildHeaders(),
      credentials: "include",
      // Include cookies for session auth
      body: JSON.stringify(data)
    });
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      let userMessage = `Error al crear ${entityType}`;
      if (response.status === 401) {
        userMessage = "No tienes permisos para crear este elemento. Por favor, inicia sesi\xF3n nuevamente.";
      } else if (response.status === 403) {
        userMessage = "No tienes los permisos necesarios para crear este elemento.";
      } else if (response.status === 400) {
        userMessage = "Los datos proporcionados no son v\xE1lidos. Por favor, revisa el formulario.";
      } else if (response.status >= 500) {
        userMessage = "Error interno del servidor. Por favor, intenta m\xE1s tarde.";
      } else if (errorData.message && !errorData.message.includes("API key")) {
        userMessage = errorData.message;
      }
      throw new Error(userMessage);
    }
    const result = await response.json();
    return result.data;
  }
  /**
   * Update entity
   */
  async update(entityType, id, data) {
    const endpointPath = await this.getEndpointPath(entityType);
    const response = await fetch(`${this.baseUrl}/${endpointPath}/${id}`, {
      method: "PATCH",
      headers: buildHeaders(),
      credentials: "include",
      // Include cookies for session auth
      body: JSON.stringify(data)
    });
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      let userMessage = `Error al actualizar ${entityType}`;
      if (response.status === 401) {
        userMessage = "No tienes permisos para actualizar este elemento. Por favor, inicia sesi\xF3n nuevamente.";
      } else if (response.status === 403) {
        userMessage = "No tienes los permisos necesarios para actualizar este elemento.";
      } else if (response.status === 404) {
        userMessage = "El elemento que intentas actualizar no fue encontrado.";
      } else if (response.status === 400) {
        userMessage = "Los datos proporcionados no son v\xE1lidos. Por favor, revisa el formulario.";
      } else if (response.status >= 500) {
        userMessage = "Error interno del servidor. Por favor, intenta m\xE1s tarde.";
      } else if (errorData.message && !errorData.message.includes("API key")) {
        userMessage = errorData.message;
      }
      throw new Error(userMessage);
    }
    const result = await response.json();
    return result.data;
  }
  /**
   * Delete entity
   */
  async delete(entityType, id) {
    const endpointPath = await this.getEndpointPath(entityType);
    const response = await fetch(`${this.baseUrl}/${endpointPath}/${id}`, {
      method: "DELETE",
      headers: buildHeaders(),
      credentials: "include"
      // Include cookies for session auth
    });
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      let userMessage = `Error al eliminar ${entityType}`;
      if (response.status === 401) {
        userMessage = "No tienes permisos para eliminar este elemento. Por favor, inicia sesi\xF3n nuevamente.";
      } else if (response.status === 403) {
        userMessage = "No tienes los permisos necesarios para eliminar este elemento.";
      } else if (response.status === 404) {
        userMessage = "El elemento que intentas eliminar no fue encontrado.";
      } else if (response.status >= 500) {
        userMessage = "Error interno del servidor. Por favor, intenta m\xE1s tarde.";
      } else if (errorData.message && !errorData.message.includes("API key")) {
        userMessage = errorData.message;
      }
      throw new Error(userMessage);
    }
    const result = await response.json();
    return result.data;
  }
  // ========================================
  // DASHBOARD-SPECIFIC METHODS
  // ========================================
  /**
   * Get dashboard data with stats and bulk operations
   * Optimized for dashboard views with additional metadata
   */
  async getDashboardData(entityType, params = {}) {
    try {
      const listResponse = await this.list(entityType, params);
      const [stats, operations] = await Promise.all([
        this.getEntityStats(entityType),
        this.getBulkOperations(entityType)
      ]);
      const hasOverride = this.detectEntityOverride(entityType);
      return {
        success: true,
        data: listResponse.data,
        stats,
        availableOperations: operations,
        info: {
          timestamp: (/* @__PURE__ */ new Date()).toISOString(),
          entityType,
          hasOverride
        }
      };
    } catch (error) {
      console.error(`[EntityApiClient] Error getting dashboard data for ${entityType}:`, error);
      throw error;
    }
  }
  /**
   * Get entity statistics for dashboard metrics
   */
  async getEntityStats(entityType) {
    try {
      const endpointPath = await this.getEndpointPath(entityType);
      const response = await fetch(`${this.baseUrl}/${endpointPath}/stats`, {
        method: "GET",
        headers: buildHeaders(),
        credentials: "include"
      });
      if (!response.ok) {
        console.warn(`Stats endpoint not available for ${entityType}, calculating basic stats`);
        return this.calculateBasicStats(entityType);
      }
      const result = await response.json();
      return result.data;
    } catch (error) {
      console.warn(`Error getting stats for ${entityType}, falling back to basic stats:`, error);
      return this.calculateBasicStats(entityType);
    }
  }
  /**
   * Calculate basic stats from entity list (fallback)
   */
  async calculateBasicStats(entityType) {
    try {
      const response = await this.list(entityType, { limit: 100 });
      const total = parseInt(response.info.total.toString());
      const oneWeekAgo = /* @__PURE__ */ new Date();
      oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
      const recentCount = response.data.filter((item) => {
        const createdAt = item.createdAt ? new Date(item.createdAt) : null;
        return createdAt && createdAt > oneWeekAgo;
      }).length;
      return {
        total,
        recentCount,
        growth: total > 0 ? recentCount / total * 100 : 0
      };
    } catch (error) {
      console.error(`Error calculating basic stats for ${entityType}:`, error);
      return {
        total: 0,
        recentCount: 0,
        growth: 0
      };
    }
  }
  /**
   * Get available bulk operations for entity
   */
  async getBulkOperations(entityType) {
    try {
      const entities = clientMetaSystemAdapter.getAllEntityConfigs();
      const entityConfig = entities.find((config) => config.name === entityType);
      if (!(entityConfig == null ? void 0 : entityConfig.features.enabled)) {
        return [];
      }
      const operations = [];
      if (entityConfig.features.canDelete) {
        operations.push({
          id: "bulk-delete",
          name: "Eliminar Seleccionados",
          description: "Eliminar m\xFAltiples elementos a la vez",
          icon: "trash",
          requiresConfirmation: true
        });
      }
      if (entityConfig.features.canEdit) {
        operations.push({
          id: "bulk-edit",
          name: "Editar Seleccionados",
          description: "Actualizar m\xFAltiples elementos a la vez",
          icon: "edit"
        });
      }
      operations.push({
        id: "bulk-export",
        name: "Exportar",
        description: "Exportar datos seleccionados",
        icon: "download"
      });
      return operations;
    } catch (error) {
      console.error(`Error getting bulk operations for ${entityType}:`, error);
      return [];
    }
  }
  /**
   * Execute bulk operation on multiple entities
   */
  async executeBulkOperation(entityType, operationId, entityIds, params) {
    const endpointPath = await this.getEndpointPath(entityType);
    const response = await fetch(`${this.baseUrl}/${endpointPath}/bulk`, {
      method: "POST",
      headers: buildHeaders(),
      credentials: "include",
      body: JSON.stringify({
        operation: operationId,
        entityIds,
        params
      })
    });
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Error ejecutando operaci\xF3n ${operationId}`);
    }
    const result = await response.json();
    return result.data;
  }
  /**
   * Get entity activity/audit log for dashboard
   */
  async getEntityActivity(entityType, limit = 10) {
    try {
      const endpointPath = await this.getEndpointPath(entityType);
      const response = await fetch(`${this.baseUrl}/${endpointPath}/activity?limit=${limit}`, {
        method: "GET",
        headers: buildHeaders(),
        credentials: "include"
      });
      if (!response.ok) {
        return [];
      }
      const result = await response.json();
      return result.data || [];
    } catch (error) {
      console.warn(`Activity endpoint not available for ${entityType}:`, error);
      return [];
    }
  }
  /**
   * Detect if entity has custom override (client-side detection)
   */
  detectEntityOverride(entityType) {
    const knownOverrides = ["tasks"];
    return knownOverrides.includes(entityType.toLowerCase());
  }
}
const entityApi = new EntityApiClient();
const createEntityData = async (entityType, data) => {
  return entityApi.create(entityType, data);
};
const updateEntityData = async (entityType, id, data) => {
  return entityApi.update(entityType, id, data);
};
const deleteEntityData = async (entityType, id) => {
  return entityApi.delete(entityType, id);
};
const getEntityData = async (entityType, id, includeMeta = false) => {
  return entityApi.get(entityType, id, includeMeta);
};
const listEntityData = async (entityType, params = {}) => {
  return entityApi.list(entityType, params);
};
const getEntityChildren = async (parentEntityType, parentId, childEntityName, params = {}) => {
  const apiPath = clientMetaSystemAdapter.getApiPath(parentEntityType);
  const endpointPath = apiPath || (parentEntityType.endsWith("s") ? parentEntityType : `${parentEntityType}s`);
  const baseUrl = "/api/v1";
  const url = new URL(`${baseUrl}/${endpointPath}/${parentId}/child/${childEntityName}`, getApiBaseUrl());
  if (params.page) url.searchParams.set("page", params.page.toString());
  if (params.limit) url.searchParams.set("limit", params.limit.toString());
  if (params.includeMeta) url.searchParams.set("metas", "all");
  const response = await fetch(url.toString(), {
    method: "GET",
    headers: buildHeaders(),
    credentials: "include"
  });
  if (!response.ok) {
    const errorData = await response.json().catch(() => ({}));
    throw new Error(errorData.message || `Error loading ${childEntityName} for ${parentEntityType}`);
  }
  const result = await response.json();
  return result.data;
};
async function fetchWithTeam(url, options = {}) {
  const activeTeamId = typeof window !== "undefined" ? localStorage.getItem("activeTeamId") : null;
  const headers = new Headers(options.headers || {});
  if (!headers.has("Content-Type") && options.method !== "GET") {
    headers.set("Content-Type", "application/json");
  }
  if (activeTeamId) {
    headers.set("x-team-id", activeTeamId);
  }
  return fetch(url, {
    ...options,
    headers,
    credentials: "include"
  });
}
export {
  EntityApiClient,
  createEntityData,
  deleteEntityData,
  entityApi,
  fetchWithTeam,
  getEntityChildren,
  getEntityData,
  listEntityData,
  updateEntityData
};
