import { z } from "zod";
import { findOneWithDecryption, findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import {
  CustomerDictionaryEntry,
  CustomerPipeline,
  CustomerPipelineStage,
  CustomerSettings
} from "../data/entities.js";
import { assertTenantScope } from "./types.js";
function resolveEm(ctx) {
  return ctx.container.resolve("em");
}
function buildScope(ctx, tenantId) {
  return { tenantId, organizationId: ctx.organizationId };
}
const getSettingsInput = z.object({}).passthrough();
const listPipelineStagesInput = z.object({
  pipelineId: z.string().uuid().optional().describe("Optional pipeline id to restrict returned stages.")
}).passthrough();
const getSettingsTool = {
  name: "customers.get_settings",
  displayName: "Get customers module settings",
  description: "Return the customers module settings for the caller scope: pipelines, pipeline stages, dictionaries (grouped by kind), and address format.",
  inputSchema: getSettingsInput,
  requiredFeatures: ["customers.settings.manage"],
  tags: ["read", "customers"],
  handler: async (_rawInput, ctx) => {
    const { tenantId } = assertTenantScope(ctx);
    const em = resolveEm(ctx);
    const where = { tenantId };
    if (ctx.organizationId) where.organizationId = ctx.organizationId;
    const [pipelines, stages, dictionaryEntries, settings] = await Promise.all([
      findWithDecryption(
        em,
        CustomerPipeline,
        where,
        { orderBy: { createdAt: "asc" } },
        buildScope(ctx, tenantId)
      ),
      findWithDecryption(
        em,
        CustomerPipelineStage,
        where,
        { orderBy: { pipelineId: "asc", order: "asc" } },
        buildScope(ctx, tenantId)
      ),
      findWithDecryption(
        em,
        CustomerDictionaryEntry,
        where,
        { orderBy: { kind: "asc", label: "asc" } },
        buildScope(ctx, tenantId)
      ),
      ctx.organizationId ? findOneWithDecryption(
        em,
        CustomerSettings,
        { tenantId, organizationId: ctx.organizationId },
        void 0,
        buildScope(ctx, tenantId)
      ) : null
    ]);
    const pipelineRows = pipelines.filter((row) => row.tenantId === tenantId);
    const stageRows = stages.filter((row) => row.tenantId === tenantId);
    const dictionaryRows = dictionaryEntries.filter((row) => row.tenantId === tenantId);
    const dictionaries = {};
    for (const row of dictionaryRows) {
      const bucket = dictionaries[row.kind] ?? (dictionaries[row.kind] = []);
      bucket.push({
        id: row.id,
        value: row.value,
        label: row.label,
        normalizedValue: row.normalizedValue,
        color: row.color ?? null,
        icon: row.icon ?? null
      });
    }
    return {
      pipelines: pipelineRows.map((row) => ({
        id: row.id,
        name: row.name,
        isDefault: !!row.isDefault,
        organizationId: row.organizationId ?? null,
        tenantId: row.tenantId ?? null,
        createdAt: row.createdAt ? new Date(row.createdAt).toISOString() : null
      })),
      pipelineStages: stageRows.map((row) => ({
        id: row.id,
        pipelineId: row.pipelineId,
        label: row.label,
        order: row.order,
        organizationId: row.organizationId ?? null,
        tenantId: row.tenantId ?? null
      })),
      dictionaries,
      addressFormat: settings?.addressFormat ?? "line_first"
    };
  }
};
const listPipelineStagesTool = {
  name: "customers.list_pipeline_stages",
  displayName: "List customer pipeline stages",
  description: "Return customer deal pipelines and their pipeline stages, including stage ids. Use this before moving a deal to a named pipeline stage.",
  inputSchema: listPipelineStagesInput,
  requiredFeatures: ["customers.pipelines.view"],
  tags: ["read", "customers", "pipelines"],
  isMutation: false,
  handler: async (rawInput, ctx) => {
    const { tenantId } = assertTenantScope(ctx);
    const input = listPipelineStagesInput.parse(rawInput);
    const em = resolveEm(ctx);
    const where = { tenantId };
    if (ctx.organizationId) where.organizationId = ctx.organizationId;
    const stageWhere = { ...where };
    if (input.pipelineId) stageWhere.pipelineId = input.pipelineId;
    const [pipelines, stages] = await Promise.all([
      findWithDecryption(
        em,
        CustomerPipeline,
        where,
        { orderBy: { createdAt: "asc" } },
        buildScope(ctx, tenantId)
      ),
      findWithDecryption(
        em,
        CustomerPipelineStage,
        stageWhere,
        { orderBy: { pipelineId: "asc", order: "asc" } },
        buildScope(ctx, tenantId)
      )
    ]);
    return {
      pipelines: pipelines.filter((row) => row.tenantId === tenantId).map((row) => ({
        id: row.id,
        name: row.name,
        isDefault: !!row.isDefault,
        organizationId: row.organizationId ?? null,
        tenantId: row.tenantId ?? null
      })),
      pipelineStages: stages.filter((row) => row.tenantId === tenantId).map((row) => ({
        id: row.id,
        pipelineId: row.pipelineId,
        label: row.label,
        order: row.order,
        organizationId: row.organizationId ?? null,
        tenantId: row.tenantId ?? null
      }))
    };
  }
};
const settingsAiTools = [getSettingsTool, listPipelineStagesTool];
var settings_pack_default = settingsAiTools;
export {
  settings_pack_default as default,
  settingsAiTools
};
//# sourceMappingURL=settings-pack.js.map
