"use server";
import { revalidatePath, revalidateTag } from "next/cache";
import { headers, cookies } from "next/headers";
import { redirect } from "next/navigation";
import { GenericEntityService } from "../services/generic-entity.service.js";
import { entityRegistry } from "../entities/registry.js";
import { getTypedSession } from "../auth.js";
import { checkPermission } from "../permissions/check.js";
async function getAuthContext() {
  var _a, _b;
  const headersList = await headers();
  const session = await getTypedSession(headersList);
  if (!((_a = session == null ? void 0 : session.user) == null ? void 0 : _a.id)) {
    return { success: false, error: "Authentication required" };
  }
  const cookieStore = await cookies();
  const teamId = (_b = cookieStore.get("activeTeamId")) == null ? void 0 : _b.value;
  if (!teamId) {
    return { success: false, error: "No active team selected" };
  }
  return { success: true, userId: session.user.id, teamId };
}
async function createEntity(entitySlug, data, config) {
  try {
    const entityConfig = entityRegistry.get(entitySlug);
    if (!entityConfig) {
      return {
        success: false,
        error: `Entity "${entitySlug}" not found in registry`
      };
    }
    const authContext = await getAuthContext();
    if (!authContext.success) {
      return { success: false, error: authContext.error };
    }
    const { userId, teamId } = authContext;
    const hasPermission = await checkPermission(userId, teamId, `${entitySlug}.create`);
    if (!hasPermission) {
      return { success: false, error: "Permission denied" };
    }
    const result = await GenericEntityService.create(
      entitySlug,
      userId,
      teamId,
      data
    );
    revalidatePath(`/dashboard/${entitySlug}`);
    if (config == null ? void 0 : config.revalidatePaths) {
      config.revalidatePaths.forEach((path) => revalidatePath(path));
    }
    if (config == null ? void 0 : config.revalidateTags) {
      config.revalidateTags.forEach((tag) => revalidateTag(tag));
    }
    if (config == null ? void 0 : config.redirectTo) {
      redirect(config.redirectTo);
    }
    return { success: true, data: result };
  } catch (error) {
    console.error(`[createEntity] Error creating ${entitySlug}:`, error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "Unknown error"
    };
  }
}
async function updateEntity(entitySlug, id, data, config) {
  try {
    if (!(id == null ? void 0 : id.trim())) {
      return { success: false, error: "Entity ID is required" };
    }
    const entityConfig = entityRegistry.get(entitySlug);
    if (!entityConfig) {
      return {
        success: false,
        error: `Entity "${entitySlug}" not found in registry`
      };
    }
    const authContext = await getAuthContext();
    if (!authContext.success) {
      return { success: false, error: authContext.error };
    }
    const { userId, teamId } = authContext;
    const hasPermission = await checkPermission(userId, teamId, `${entitySlug}.update`);
    if (!hasPermission) {
      return { success: false, error: "Permission denied" };
    }
    const result = await GenericEntityService.update(
      entitySlug,
      id,
      userId,
      data,
      teamId
    );
    revalidatePath(`/dashboard/${entitySlug}`);
    revalidatePath(`/dashboard/${entitySlug}/${id}`);
    if (config == null ? void 0 : config.revalidatePaths) {
      config.revalidatePaths.forEach((path) => revalidatePath(path));
    }
    if (config == null ? void 0 : config.revalidateTags) {
      config.revalidateTags.forEach((tag) => revalidateTag(tag));
    }
    if (config == null ? void 0 : config.redirectTo) {
      redirect(config.redirectTo);
    }
    return { success: true, data: result };
  } catch (error) {
    console.error(`[updateEntity] Error updating ${entitySlug}/${id}:`, error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "Unknown error"
    };
  }
}
async function deleteEntity(entitySlug, id, config) {
  try {
    if (!(id == null ? void 0 : id.trim())) {
      return { success: false, error: "Entity ID is required" };
    }
    const entityConfig = entityRegistry.get(entitySlug);
    if (!entityConfig) {
      return {
        success: false,
        error: `Entity "${entitySlug}" not found in registry`
      };
    }
    const authContext = await getAuthContext();
    if (!authContext.success) {
      return { success: false, error: authContext.error };
    }
    const { userId, teamId } = authContext;
    const hasPermission = await checkPermission(userId, teamId, `${entitySlug}.delete`);
    if (!hasPermission) {
      return { success: false, error: "Permission denied" };
    }
    const deleted = await GenericEntityService.delete(entitySlug, id, userId, teamId);
    if (!deleted) {
      return { success: false, error: "Entity not found or not authorized" };
    }
    revalidatePath(`/dashboard/${entitySlug}`);
    if (config == null ? void 0 : config.revalidatePaths) {
      config.revalidatePaths.forEach((path) => revalidatePath(path));
    }
    if (config == null ? void 0 : config.revalidateTags) {
      config.revalidateTags.forEach((tag) => revalidateTag(tag));
    }
    if (config == null ? void 0 : config.redirectTo) {
      redirect(config.redirectTo);
    }
    return { success: true };
  } catch (error) {
    console.error(`[deleteEntity] Error deleting ${entitySlug}/${id}:`, error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "Unknown error"
    };
  }
}
async function getEntity(entitySlug, id) {
  try {
    if (!(id == null ? void 0 : id.trim())) {
      return { success: false, error: "Entity ID is required" };
    }
    const entityConfig = entityRegistry.get(entitySlug);
    if (!entityConfig) {
      return {
        success: false,
        error: `Entity "${entitySlug}" not found in registry`
      };
    }
    const authContext = await getAuthContext();
    if (!authContext.success) {
      return { success: false, error: authContext.error };
    }
    const { userId, teamId } = authContext;
    const hasPermission = await checkPermission(userId, teamId, `${entitySlug}.read`);
    if (!hasPermission) {
      return { success: false, error: "Permission denied" };
    }
    const result = await GenericEntityService.getById(entitySlug, id, userId, teamId);
    return { success: true, data: result };
  } catch (error) {
    console.error(`[getEntity] Error fetching ${entitySlug}/${id}:`, error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "Unknown error"
    };
  }
}
async function listEntities(entitySlug, options) {
  try {
    const entityConfig = entityRegistry.get(entitySlug);
    if (!entityConfig) {
      return {
        success: false,
        error: `Entity "${entitySlug}" not found in registry`
      };
    }
    const authContext = await getAuthContext();
    if (!authContext.success) {
      return { success: false, error: authContext.error };
    }
    const { userId, teamId } = authContext;
    const hasPermission = await checkPermission(userId, teamId, `${entitySlug}.list`);
    if (!hasPermission) {
      return { success: false, error: "Permission denied" };
    }
    const result = await GenericEntityService.list(entitySlug, userId, {
      ...options,
      teamId
    });
    return { success: true, data: result };
  } catch (error) {
    console.error(`[listEntities] Error listing ${entitySlug}:`, error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "Unknown error"
    };
  }
}
async function deleteEntities(entitySlug, ids, config) {
  try {
    if (!(ids == null ? void 0 : ids.length)) {
      return { success: false, error: "At least one ID is required" };
    }
    const entityConfig = entityRegistry.get(entitySlug);
    if (!entityConfig) {
      return {
        success: false,
        error: `Entity "${entitySlug}" not found in registry`
      };
    }
    const authContext = await getAuthContext();
    if (!authContext.success) {
      return { success: false, error: authContext.error };
    }
    const { userId, teamId } = authContext;
    const hasPermission = await checkPermission(userId, teamId, `${entitySlug}.delete`);
    if (!hasPermission) {
      return { success: false, error: "Permission denied" };
    }
    const deletedCount = await GenericEntityService.deleteMany(entitySlug, ids, userId, {
      executeHooks: true,
      // Execute hooks for each entity
      teamId
      // Team isolation
    });
    revalidatePath(`/dashboard/${entitySlug}`);
    if (config == null ? void 0 : config.revalidatePaths) {
      config.revalidatePaths.forEach((path) => revalidatePath(path));
    }
    if (config == null ? void 0 : config.revalidateTags) {
      config.revalidateTags.forEach((tag) => revalidateTag(tag));
    }
    if (config == null ? void 0 : config.redirectTo) {
      redirect(config.redirectTo);
    }
    return { success: true, data: { deletedCount } };
  } catch (error) {
    console.error(`[deleteEntities] Error batch deleting ${entitySlug}:`, error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "Unknown error"
    };
  }
}
async function entityExists(entitySlug, id) {
  try {
    if (!(id == null ? void 0 : id.trim())) {
      return { success: false, error: "Entity ID is required" };
    }
    const entityConfig = entityRegistry.get(entitySlug);
    if (!entityConfig) {
      return {
        success: false,
        error: `Entity "${entitySlug}" not found in registry`
      };
    }
    const authContext = await getAuthContext();
    if (!authContext.success) {
      return { success: false, error: authContext.error };
    }
    const { userId, teamId } = authContext;
    const hasPermission = await checkPermission(userId, teamId, `${entitySlug}.read`);
    if (!hasPermission) {
      return { success: false, error: "Permission denied" };
    }
    const exists = await GenericEntityService.exists(entitySlug, id, userId, teamId);
    return { success: true, data: exists };
  } catch (error) {
    console.error(`[entityExists] Error checking ${entitySlug}/${id}:`, error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "Unknown error"
    };
  }
}
async function countEntities(entitySlug, where) {
  try {
    const entityConfig = entityRegistry.get(entitySlug);
    if (!entityConfig) {
      return {
        success: false,
        error: `Entity "${entitySlug}" not found in registry`
      };
    }
    const authContext = await getAuthContext();
    if (!authContext.success) {
      return { success: false, error: authContext.error };
    }
    const { userId, teamId } = authContext;
    const hasPermission = await checkPermission(userId, teamId, `${entitySlug}.list`);
    if (!hasPermission) {
      return { success: false, error: "Permission denied" };
    }
    const count = await GenericEntityService.count(entitySlug, userId, { ...where, teamId });
    return { success: true, data: count };
  } catch (error) {
    console.error(`[countEntities] Error counting ${entitySlug}:`, error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "Unknown error"
    };
  }
}
export {
  countEntities,
  createEntity,
  deleteEntities,
  deleteEntity,
  entityExists,
  getEntity,
  listEntities,
  updateEntity
};
