import { z } from "zod";
import { makeCrudRoute } from "@open-mercato/shared/lib/crud/factory";
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
import { resolveCrudRecordId, parseScopedCommandInput } from "@open-mercato/shared/lib/api/scoped";
import { escapeLikePattern } from "@open-mercato/shared/lib/db/escapeLikePattern";
import { ResourcesResourceType } from "../data/entities.js";
import { resourcesResourceTypeCreateSchema, resourcesResourceTypeUpdateSchema } from "../data/validators.js";
import { sanitizeSearchTerm } from "./helpers.js";
import { attachResourceTypeCounts } from "./resourceTypeCounts.js";
import { E } from "../../../generated/entities.ids.generated.js";
import { createResourcesCrudOpenApi, createPagedListResponseSchema, defaultOkResponseSchema } from "./openapi.js";
const F = {
  id: "id",
  tenant_id: "tenant_id",
  organization_id: "organization_id",
  name: "name",
  description: "description",
  default_duration: "default_duration",
  default_buffer: "default_buffer",
  appearance_icon: "appearance_icon",
  appearance_color: "appearance_color",
  is_active: "is_active",
  created_at: "created_at",
  updated_at: "updated_at",
  deleted_at: "deleted_at"
};
const routeMetadata = {
  GET: { requireAuth: true, requireFeatures: ["resources.view"] },
  POST: { requireAuth: true, requireFeatures: ["resources.manage_resources"] },
  PUT: { requireAuth: true, requireFeatures: ["resources.manage_resources"] },
  DELETE: { requireAuth: true, requireFeatures: ["resources.manage_resources"] }
};
const metadata = routeMetadata;
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),
  search: z.string().optional(),
  ids: z.string().optional(),
  sortField: z.string().optional(),
  sortDir: z.enum(["asc", "desc"]).optional(),
  withResourceCounts: z.string().optional()
}).passthrough();
const crud = makeCrudRoute({
  metadata: routeMetadata,
  orm: {
    entity: ResourcesResourceType,
    idField: "id",
    orgField: "organizationId",
    tenantField: "tenantId",
    softDeleteField: "deletedAt"
  },
  indexer: { entityType: E.resources.resources_resource_type },
  list: {
    schema: listSchema,
    entityId: E.resources.resources_resource_type,
    fields: [
      F.id,
      F.organization_id,
      F.tenant_id,
      F.name,
      F.description,
      "appearance_icon",
      "appearance_color",
      F.created_at,
      F.updated_at
    ],
    sortFieldMap: {
      name: F.name,
      createdAt: F.created_at,
      updatedAt: F.updated_at
    },
    buildFilters: async (query) => {
      const filters = {};
      if (typeof query.ids === "string" && query.ids.trim().length > 0) {
        const ids = query.ids.split(",").map((value) => value.trim()).filter((value) => value.length > 0);
        if (ids.length > 0) {
          filters[F.id] = { $in: ids };
        }
      }
      const term = sanitizeSearchTerm(query.search);
      if (term) {
        const like = `%${escapeLikePattern(term)}%`;
        filters[F.name] = { $ilike: like };
      }
      return filters;
    },
    decorateCustomFields: { entityIds: [E.resources.resources_resource_type] }
  },
  actions: {
    create: {
      commandId: "resources.resourceTypes.create",
      schema: rawBodySchema,
      mapInput: async ({ raw, ctx }) => {
        const { translate } = await resolveTranslations();
        return parseScopedCommandInput(resourcesResourceTypeCreateSchema, raw ?? {}, ctx, translate);
      },
      response: ({ result }) => ({ id: result?.resourceTypeId ?? null }),
      status: 201
    },
    update: {
      commandId: "resources.resourceTypes.update",
      schema: rawBodySchema,
      mapInput: async ({ raw, ctx }) => {
        const { translate } = await resolveTranslations();
        return parseScopedCommandInput(resourcesResourceTypeUpdateSchema, raw ?? {}, ctx, translate);
      },
      response: () => ({ ok: true })
    },
    delete: {
      commandId: "resources.resourceTypes.delete",
      schema: rawBodySchema,
      mapInput: async ({ parsed, ctx }) => {
        const { translate } = await resolveTranslations();
        const id = resolveCrudRecordId(parsed, ctx, translate);
        return { id };
      },
      response: () => ({ ok: true })
    }
  },
  hooks: {
    afterList: (payload, ctx) => attachResourceTypeCounts(payload, ctx)
  }
});
const GET = crud.GET;
const POST = crud.POST;
const PUT = crud.PUT;
const DELETE = crud.DELETE;
const resourceTypeListItemSchema = z.object({
  id: z.string().uuid().nullable().optional(),
  organization_id: z.string().uuid().nullable().optional(),
  tenant_id: z.string().uuid().nullable().optional(),
  name: z.string().nullable().optional(),
  description: z.string().nullable().optional(),
  appearance_icon: z.string().nullable().optional(),
  appearance_color: z.string().nullable().optional(),
  created_at: z.string().nullable().optional(),
  updated_at: z.string().nullable().optional(),
  resourceCount: z.number().nullable().optional()
});
const openApi = createResourcesCrudOpenApi({
  resourceName: "Resource type",
  pluralName: "Resource types",
  querySchema: listSchema,
  listResponseSchema: createPagedListResponseSchema(resourceTypeListItemSchema),
  create: {
    schema: resourcesResourceTypeCreateSchema,
    description: "Creates a resource type for resources resources."
  },
  update: {
    schema: resourcesResourceTypeUpdateSchema,
    responseSchema: defaultOkResponseSchema,
    description: "Updates a resource type by id."
  },
  del: {
    schema: z.object({ id: z.string().uuid() }),
    responseSchema: defaultOkResponseSchema,
    description: "Deletes a resource type by id."
  }
});
export {
  DELETE,
  GET,
  POST,
  PUT,
  metadata,
  openApi
};
//# sourceMappingURL=resource-types.js.map
