import { z } from "zod";
import { makeCrudRoute } from "@open-mercato/shared/lib/crud/factory";
import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
import { findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { CustomerComment, CustomerDeal } from "../../data/entities.js";
import { commentCreateSchema, commentUpdateSchema } from "../../data/validators.js";
import { E } from "../../../../generated/entities.ids.generated.js";
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
import { withScopedPayload } from "../utils.js";
import {
  createCustomersCrudOpenApi,
  createPagedListResponseSchema,
  defaultOkResponseSchema
} from "../openapi.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("customers");
const rawBodySchema = z.object({}).passthrough();
const listSchema = z.object({
  page: z.coerce.number().min(1).default(1),
  pageSize: z.coerce.number().min(1).max(100).default(50),
  entityId: z.string().uuid().optional(),
  dealId: z.string().uuid().optional(),
  sortField: z.string().optional(),
  sortDir: z.enum(["asc", "desc"]).optional()
}).passthrough();
const routeMetadata = {
  GET: { requireAuth: true, requireFeatures: ["customers.activities.view"] },
  POST: { requireAuth: true, requireFeatures: ["customers.activities.manage"] },
  PUT: { requireAuth: true, requireFeatures: ["customers.activities.manage"] },
  DELETE: { requireAuth: true, requireFeatures: ["customers.activities.manage"] }
};
const metadata = routeMetadata;
const crud = makeCrudRoute({
  metadata: routeMetadata,
  orm: {
    entity: CustomerComment,
    idField: "id",
    orgField: "organizationId",
    tenantField: "tenantId",
    softDeleteField: "deletedAt"
  },
  indexer: {
    entityType: E.customers.customer_comment
  },
  list: {
    schema: listSchema,
    entityId: E.customers.customer_comment,
    fields: [
      "id",
      "entity_id",
      "deal_id",
      "body",
      "author_user_id",
      "appearance_icon",
      "appearance_color",
      "organization_id",
      "tenant_id",
      "created_at",
      "updated_at"
    ],
    sortFieldMap: {
      createdAt: "created_at",
      updatedAt: "updated_at"
    },
    buildFilters: async (query) => {
      const filters = {};
      if (query.entityId) filters.entity_id = { $eq: query.entityId };
      if (query.dealId) filters.deal_id = { $eq: query.dealId };
      return filters;
    }
  },
  actions: {
    create: {
      commandId: "customers.comments.create",
      schema: rawBodySchema,
      mapInput: async ({ raw, ctx }) => {
        const { translate } = await resolveTranslations();
        return commentCreateSchema.parse(withScopedPayload(raw ?? {}, ctx, translate));
      },
      response: ({ result }) => ({
        id: result?.commentId ?? result?.id ?? null,
        authorUserId: result?.authorUserId ?? null
      }),
      status: 201
    },
    update: {
      commandId: "customers.comments.update",
      schema: rawBodySchema,
      mapInput: async ({ raw, ctx }) => {
        const { translate } = await resolveTranslations();
        return commentUpdateSchema.parse(withScopedPayload(raw ?? {}, ctx, translate));
      },
      response: () => ({ ok: true })
    },
    delete: {
      commandId: "customers.comments.delete",
      schema: rawBodySchema,
      mapInput: async ({ parsed, ctx }) => {
        const { translate } = await resolveTranslations();
        const id = parsed?.body?.id ?? parsed?.id ?? parsed?.query?.id ?? (ctx.request ? new URL(ctx.request.url).searchParams.get("id") : null);
        if (!id) throw new CrudHttpError(400, { error: translate("customers.errors.comment_required", "Comment id is required") });
        return { id };
      },
      response: () => ({ ok: true })
    }
  },
  hooks: {
    afterList: async (payload, ctx) => {
      const items = Array.isArray(payload.items) ? payload.items : [];
      if (!items.length) return;
      const dealIds = Array.from(
        new Set(
          items.map((item) => {
            if (!item || typeof item !== "object") return null;
            const record = item;
            const raw = typeof record.deal_id === "string" ? record.deal_id : typeof record.dealId === "string" ? record.dealId : null;
            return raw && raw.trim().length ? raw : null;
          }).filter(
            (value) => typeof value === "string" && value.length > 0
          )
        )
      );
      if (!dealIds.length) return;
      const tenantId = ctx.auth?.tenantId ?? null;
      const organizationId = ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null;
      if (!tenantId || !organizationId) {
        const { translate } = await resolveTranslations();
        throw new CrudHttpError(400, {
          error: translate("customers.errors.tenant_required", "Tenant context is required")
        });
      }
      try {
        const em = ctx.container.resolve("em");
        const deals = await findWithDecryption(
          em,
          CustomerDeal,
          { id: { $in: dealIds }, tenantId, organizationId },
          void 0,
          { tenantId, organizationId }
        );
        const map = /* @__PURE__ */ new Map();
        deals.forEach((deal) => {
          if (deal.id) map.set(deal.id, deal.title ?? "");
        });
        items.forEach((item) => {
          if (!item || typeof item !== "object") return;
          const record = item;
          const raw = typeof record.deal_id === "string" ? record.deal_id : typeof record.dealId === "string" ? record.dealId : null;
          if (!raw) return;
          const title = map.get(raw) ?? null;
          record.dealTitle = title;
          if (!("deal_title" in record)) {
            ;
            record.deal_title = title;
          }
        });
      } catch (err) {
        logger.warn("failed to enrich deal titles", { component: "comments", err });
      }
    }
  }
});
const { POST, PUT, DELETE } = crud;
const GET = crud.GET;
const commentListItemSchema = z.object({
  id: z.string().uuid(),
  entity_id: z.string().uuid().nullable(),
  deal_id: z.string().uuid().nullable(),
  body: z.string().nullable(),
  author_user_id: z.string().uuid().nullable(),
  appearance_icon: z.string().nullable().optional(),
  appearance_color: z.string().nullable().optional(),
  organization_id: z.string().uuid().nullable().optional(),
  tenant_id: z.string().uuid().nullable().optional(),
  created_at: z.string().nullable(),
  updated_at: z.string().nullable().optional()
}).passthrough();
const commentCreateResponseSchema = z.object({
  id: z.string().uuid().nullable(),
  authorUserId: z.string().uuid().nullable()
});
const openApi = createCustomersCrudOpenApi({
  resourceName: "Comment",
  querySchema: listSchema,
  listResponseSchema: createPagedListResponseSchema(commentListItemSchema),
  create: {
    schema: commentCreateSchema,
    responseSchema: commentCreateResponseSchema,
    description: "Adds a comment to a customer timeline."
  },
  update: {
    schema: commentUpdateSchema,
    responseSchema: defaultOkResponseSchema,
    description: "Updates an existing timeline comment."
  },
  del: {
    schema: z.object({ id: z.string().uuid() }),
    responseSchema: defaultOkResponseSchema,
    description: "Deletes a comment identified by `id` supplied via body or query string."
  }
});
export {
  DELETE,
  GET,
  POST,
  PUT,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
