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 { findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { StaffTeam, StaffTeamMember, StaffTeamRole } from "../data/entities.js";
import { staffTeamRoleCreateSchema, staffTeamRoleUpdateSchema } from "../data/validators.js";
import { sanitizeSearchTerm } from "./helpers.js";
import { E } from "../../../generated/entities.ids.generated.js";
import { createStaffCrudOpenApi, createPagedListResponseSchema, defaultOkResponseSchema } from "./openapi.js";
const F = {
  id: "id",
  tenant_id: "tenant_id",
  organization_id: "organization_id",
  team_id: "team_id",
  name: "name",
  description: "description",
  appearance_icon: "appearance_icon",
  appearance_color: "appearance_color",
  created_at: "created_at",
  updated_at: "updated_at",
  deleted_at: "deleted_at"
};
const routeMetadata = {
  GET: { requireAuth: true, requireFeatures: ["staff.view"] },
  POST: { requireAuth: true, requireFeatures: ["staff.manage_team"] },
  PUT: { requireAuth: true, requireFeatures: ["staff.manage_team"] },
  DELETE: { requireAuth: true, requireFeatures: ["staff.manage_team"] }
};
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(),
  teamId: z.string().uuid().optional(),
  sortField: z.string().optional(),
  sortDir: z.enum(["asc", "desc"]).optional()
}).passthrough();
const crud = makeCrudRoute({
  metadata: routeMetadata,
  orm: {
    entity: StaffTeamRole,
    idField: "id",
    orgField: "organizationId",
    tenantField: "tenantId",
    softDeleteField: "deletedAt"
  },
  indexer: { entityType: E.staff.staff_team_role },
  list: {
    schema: listSchema,
    entityId: E.staff.staff_team_role,
    fields: [
      F.id,
      F.organization_id,
      F.tenant_id,
      F.team_id,
      F.name,
      F.description,
      F.appearance_icon,
      F.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 };
      }
      if (query.teamId) {
        filters[F.team_id] = query.teamId;
      }
      return filters;
    },
    decorateCustomFields: { entityIds: [E.staff.staff_team_role] }
  },
  hooks: {
    afterList: async (payload, ctx) => {
      const items = Array.isArray(payload?.items) ? payload.items : [];
      if (!items.length) return;
      const memberCounts = /* @__PURE__ */ new Map();
      const tenantId = ctx.auth?.tenantId ?? null;
      const organizationId = ctx.selectedOrganizationId ?? null;
      const roleIds = /* @__PURE__ */ new Set();
      const teamIds = /* @__PURE__ */ new Set();
      items.forEach((item) => {
        if (!item || typeof item !== "object") return;
        const teamId = typeof item.teamId === "string" ? item.teamId : typeof item.team_id === "string" ? item.team_id : null;
        if (teamId) teamIds.add(teamId);
        const roleId = typeof item.id === "string" && item.id.length ? item.id : null;
        if (roleId) roleIds.add(roleId);
      });
      const em = ctx.container.resolve("em").fork();
      if (roleIds.size && tenantId && organizationId) {
        const counts = await Promise.all(
          Array.from(roleIds).map(async (roleId) => {
            const count = await em.count(StaffTeamMember, {
              tenantId,
              organizationId,
              deletedAt: null,
              roleIds: { $contains: [roleId] }
            });
            return [roleId, count];
          })
        );
        counts.forEach(([roleId, count]) => {
          memberCounts.set(roleId, count);
        });
      }
      const teams = teamIds.size ? await findWithDecryption(
        em,
        StaffTeam,
        { id: { $in: Array.from(teamIds) }, deletedAt: null },
        void 0,
        { tenantId, organizationId }
      ) : [];
      const teamById = new Map(teams.map((team) => [team.id, { id: team.id, name: team.name }]));
      items.forEach((item) => {
        if (!item || typeof item !== "object") return;
        const teamId = typeof item.teamId === "string" ? item.teamId : typeof item.team_id === "string" ? item.team_id : null;
        item.team = teamId ? teamById.get(teamId) ?? null : null;
        const roleId = typeof item.id === "string" && item.id.length ? item.id : null;
        item.memberCount = roleId ? memberCounts.get(roleId) ?? 0 : 0;
      });
    }
  },
  actions: {
    create: {
      commandId: "staff.team-roles.create",
      schema: rawBodySchema,
      mapInput: async ({ raw, ctx }) => {
        const { translate } = await resolveTranslations();
        return parseScopedCommandInput(staffTeamRoleCreateSchema, raw ?? {}, ctx, translate);
      },
      response: ({ result }) => ({ id: result?.roleId ?? null }),
      status: 201
    },
    update: {
      commandId: "staff.team-roles.update",
      schema: rawBodySchema,
      mapInput: async ({ raw, ctx }) => {
        const { translate } = await resolveTranslations();
        return parseScopedCommandInput(staffTeamRoleUpdateSchema, raw ?? {}, ctx, translate);
      },
      response: () => ({ ok: true })
    },
    delete: {
      commandId: "staff.team-roles.delete",
      schema: rawBodySchema,
      mapInput: async ({ parsed, ctx }) => {
        const { translate } = await resolveTranslations();
        const id = resolveCrudRecordId(parsed, ctx, translate);
        return { id };
      },
      response: () => ({ ok: true })
    }
  }
});
const GET = crud.GET;
const POST = crud.POST;
const PUT = crud.PUT;
const DELETE = crud.DELETE;
const teamRoleListItemSchema = z.object({
  id: z.string().uuid().nullable().optional(),
  organization_id: z.string().uuid().nullable().optional(),
  tenant_id: z.string().uuid().nullable().optional(),
  team_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(),
  team: z.object({
    id: z.string().uuid().nullable().optional(),
    name: z.string().nullable().optional()
  }).nullable().optional(),
  memberCount: z.number().nullable().optional()
});
const openApi = createStaffCrudOpenApi({
  resourceName: "Team role",
  pluralName: "Team roles",
  querySchema: listSchema,
  listResponseSchema: createPagedListResponseSchema(teamRoleListItemSchema),
  create: {
    schema: staffTeamRoleCreateSchema,
    description: "Creates a team role for staff team members."
  },
  update: {
    schema: staffTeamRoleUpdateSchema,
    responseSchema: defaultOkResponseSchema,
    description: "Updates a team role by id."
  },
  del: {
    schema: z.object({ id: z.string().uuid() }),
    responseSchema: defaultOkResponseSchema,
    description: "Deletes a team role by id."
  }
});
export {
  DELETE,
  GET,
  POST,
  PUT,
  metadata,
  openApi
};
//# sourceMappingURL=team-roles.js.map
