import { z } from "zod";
import { defineApiBackedAiTool } from "@open-mercato/ai-assistant/modules/ai_assistant/lib/api-backed-tool";
import {
  createAiApiOperationRunner
} from "@open-mercato/ai-assistant/modules/ai_assistant/lib/ai-api-operation-runner";
import { assertTenantScope } from "./types.js";
import {
  buildRelatedRecords,
  toCustomerListSummary,
  toIso
} from "./_shared.js";
const listCompaniesInput = z.object({
  q: z.string().trim().optional().describe("Search text matched against display name / email / domain. Omit or leave empty to list all."),
  limit: z.number().int().min(1).max(100).optional().describe("Maximum rows to return (default 50, max 100)."),
  offset: z.number().int().min(0).optional().describe("Number of rows to skip (default 0)."),
  tags: z.array(z.string().uuid()).optional().describe("Restrict to companies carrying at least one of these tag ids.")
}).passthrough();
const listCompaniesTool = defineApiBackedAiTool({
  name: "customers.list_companies",
  displayName: "List companies",
  description: "Search / list companies for the caller tenant + organization. Returns { items, total, limit, offset }.",
  inputSchema: listCompaniesInput,
  requiredFeatures: ["customers.companies.view"],
  toOperation: (input, ctx) => {
    assertTenantScope(ctx);
    const limit = input.limit ?? 50;
    const offset = input.offset ?? 0;
    const page = Math.floor(offset / limit) + 1;
    const query = {
      page,
      pageSize: limit
    };
    if (input.q?.trim()) query.search = input.q.trim();
    if (input.tags && input.tags.length > 0) query.tagIds = input.tags.join(",");
    const operation = {
      method: "GET",
      path: "/customers/companies",
      query
    };
    return operation;
  },
  mapResponse: (response, input) => {
    const limit = input.limit ?? 50;
    const offset = input.offset ?? 0;
    const data = response.data ?? {};
    const rawItems = Array.isArray(data.items) ? data.items : [];
    return {
      items: rawItems.map((row) => ({
        ...toCustomerListSummary(row),
        domain: row.domain ?? null,
        websiteUrl: row.website_url ?? row.websiteUrl ?? null,
        industry: row.industry ?? null,
        sizeBucket: row.size_bucket ?? row.sizeBucket ?? null
      })),
      total: typeof data.total === "number" ? data.total : 0,
      limit,
      offset
    };
  }
});
const getCompanyInput = z.object({
  companyId: z.string().uuid().describe("Company entity id (UUID)."),
  includeRelated: z.boolean().optional().describe("When true, include notes, activities, deals, people, addresses, tasks, and tags (each capped at 100).")
});
const getCompanyTool = {
  name: "customers.get_company",
  displayName: "Get company",
  description: "Fetch a company customer record by id with profile fields and (optionally) notes, activities, deals, people, addresses, tasks, tags, and custom fields. Returns { found: false } when outside tenant/org scope.",
  inputSchema: getCompanyInput,
  requiredFeatures: ["customers.companies.view"],
  tags: ["read", "customers"],
  handler: async (rawInput, ctx) => {
    const { tenantId: _tenantId } = assertTenantScope(ctx);
    void _tenantId;
    const input = getCompanyInput.parse(rawInput);
    const includeRelated = !!input.includeRelated;
    const operation = {
      method: "GET",
      path: `/customers/companies/${input.companyId}`
    };
    if (includeRelated) {
      operation.query = {
        include: "addresses,comments,activities,interactions,deals,todos,people"
      };
    }
    const runner = createAiApiOperationRunner(ctx);
    const response = await runner.run(operation);
    if (!response.success) {
      if (response.statusCode === 404 || response.statusCode === 403) {
        return { found: false, companyId: input.companyId };
      }
      throw new Error(response.error ?? `Failed to fetch company ${input.companyId}`);
    }
    const data = response.data ?? {};
    const companyRow = data.company ?? null;
    if (!companyRow) {
      return { found: false, companyId: input.companyId };
    }
    const profileRow = data.profile ?? null;
    const customFields = data.customFields ?? {};
    let related = null;
    if (includeRelated) {
      related = buildRelatedRecords(data, { includePeople: true });
    }
    return {
      found: true,
      company: {
        id: companyRow.id,
        displayName: companyRow.displayName ?? null,
        description: companyRow.description ?? null,
        primaryEmail: companyRow.primaryEmail ?? null,
        primaryPhone: companyRow.primaryPhone ?? null,
        status: companyRow.status ?? null,
        lifecycleStage: companyRow.lifecycleStage ?? null,
        source: companyRow.source ?? null,
        ownerUserId: companyRow.ownerUserId ?? null,
        organizationId: companyRow.organizationId ?? null,
        tenantId: companyRow.tenantId ?? null,
        createdAt: toIso(companyRow.createdAt),
        updatedAt: toIso(companyRow.updatedAt)
      },
      profile: profileRow ? {
        id: profileRow.id,
        legalName: profileRow.legalName ?? null,
        brandName: profileRow.brandName ?? null,
        domain: profileRow.domain ?? null,
        websiteUrl: profileRow.websiteUrl ?? null,
        industry: profileRow.industry ?? null,
        sizeBucket: profileRow.sizeBucket ?? null,
        annualRevenue: profileRow.annualRevenue ?? null
      } : null,
      customFields,
      related
    };
  }
};
const companiesAiTools = [listCompaniesTool, getCompanyTool];
var companies_pack_default = companiesAiTools;
export {
  companiesAiTools,
  companies_pack_default as default
};
//# sourceMappingURL=companies-pack.js.map
