All files / routes/admin taxonomy.routes.ts

88.11% Statements 178/202
84.84% Branches 56/66
92.3% Functions 24/26
87.87% Lines 174/198

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729                                                            1x               1x 2x 2x     2x                   3x   1x   1x         1x 2x 2x 2x   2x               1x   1x         1x 2x 2x 2x   2x                     1x   1x         1x 2x 2x 2x   2x                           1x   1x                       1x       1x                                                                                                                                                                                                                                         5x     5x               2x                       3x       3x                           4x           3x 3x 4x             3x 4x 4x                   3x 3x 1x                                       1x       1x 1x                           3x 4x 4x   4x         4x                                       1x 3x 3x 3x             1x 2x 2x 2x 2x 1x         1x                   1x 4x 4x 4x       4x 4x       4x                                                           4x                           4x                     1x 17x 17x 17x   17x 17x 17x 17x     17x 17x       17x 14x         2x 1x           1x             18x   15x   2x         1x 3x 3x 3x 3x   3x 3x 3x   3x           2x 2x 1x     1x   2x         1x 5x 5x 5x   5x 5x     5x 5x   5x 5x 5x     5x     5x           1x 1x   4x         1x 2x 2x 2x 2x   2x 2x     2x   2x 2x 2x     2x           2x 1x       1x     1x             1x 1x   1x         1x 2x 2x 2x 2x   2x 2x 2x 2x     2x           2x 1x       1x           1x 1x         1x         1x 2x 2x 2x   2x 2x       2x 1x     1x 1x 1x     1x 3x       3x         1x   1x         1x          
// Admin Taxonomy Management Routes
import { Hono, type Context } from "hono";
import { eq, and, asc, sql } from "drizzle-orm";
import { z } from "zod";
import type { Dal } from "../../dal";
import type { Services } from "../../services";
import { success, handleError } from "../../lib/response";
import { requireUser } from "../../lib/utils";
import { NotFoundError, ValidationError } from "../../lib/errors";
import * as schema from "../../db/schema";
import { getDb } from "../../db";
import { createDualCache, CACHE_KEYS } from "../../lib/cache";
import {
	validateTaxonomyType,
	validateRequiredFields,
	validateEnumFields,
} from "./taxonomy.validators";
import { getStrategyForType } from "./taxonomy/taxonomy-strategy-factory";
import { logger } from "../../lib/logger";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
	};
};
 
const taxonomy = new Hono<Env>();
 
// ============================================================================
// Special Routes for Hierarchical Taxonomies
// NOTE: These must be defined BEFORE generic routes like /:type/:id
// ============================================================================
 
// Get all root-level service categories (no parent)
taxonomy.get("/serviceCategories/roots", async (c) => {
	try {
		const db = getDb(c.env.DB);
 
		// SQLite treats NULL as a unique value, so we need to check for NULL explicitly
		const allCategories = await db
			.select()
			.from(schema.serviceCategories)
			.where(eq(schema.serviceCategories.isActive, true))
			.orderBy(
				asc(schema.serviceCategories.sortOrder),
				asc(schema.serviceCategories.name),
			);
 
		// Filter for root categories (those without a parent)
		const roots = allCategories.filter((cat) => !cat.parentId);
 
		return success(c, roots);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Get zones for a specific city
taxonomy.get("/zones/by-city/:cityId", async (c) => {
	try {
		const cityId = c.req.param("cityId");
		const db = getDb(c.env.DB);
 
		const zones = await db
			.select()
			.from(schema.zones)
			.where(
				and(eq(schema.zones.cityId, cityId), eq(schema.zones.isActive, true)),
			)
			.orderBy(asc(schema.zones.sortOrder), asc(schema.zones.name));
 
		return success(c, zones);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Get localities for a specific zone
taxonomy.get("/localities/by-zone/:zoneId", async (c) => {
	try {
		const zoneId = c.req.param("zoneId");
		const db = getDb(c.env.DB);
 
		const localities = await db
			.select()
			.from(schema.localities)
			.where(
				and(
					eq(schema.localities.zoneId, zoneId),
					eq(schema.localities.isActive, true),
				),
			)
			.orderBy(asc(schema.localities.sortOrder), asc(schema.localities.name));
 
		return success(c, localities);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Get child service categories for a parent
taxonomy.get("/serviceCategories/by-parent/:parentId", async (c) => {
	try {
		const parentId = c.req.param("parentId");
		const db = getDb(c.env.DB);
 
		const children = await db
			.select()
			.from(schema.serviceCategories)
			.where(
				and(
					eq(schema.serviceCategories.parentId, parentId),
					eq(schema.serviceCategories.isActive, true),
				),
			)
			.orderBy(
				asc(schema.serviceCategories.sortOrder),
				asc(schema.serviceCategories.name),
			);
 
		return success(c, children);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// ============================================================================
// Room Category Cover Override (E9A single-statement validation)
// ============================================================================
 
// Set or clear the editorial cover image for a room category.
// E9A: single conditional UPDATE — race-free, no SELECT-then-UPDATE pattern.
// If coverMediaId is not null, validates that the media belongs to a room of
// this category in a single statement. Returns 409 if validation fails.
const roomCoverSchema = z.object({
	coverMediaId: z.number().int().positive().nullable(),
});
 
taxonomy.put("/roomTypes/:code/cover", async (c) => {
	try {
		requireUser(c.get("user"));
 
		const code = c.req.param("code");
		const body = roomCoverSchema.safeParse(await c.req.json());
		if (!body.success) {
			return c.json(
				{ success: false, error: { message: "coverMediaId must be a positive integer or null" } },
				400,
			);
		}
 
		const { coverMediaId } = body.data;
		const db = getDb(c.env.DB);
 
		// E9A: single conditional UPDATE. If coverMediaId IS NOT NULL, validate
		// inline that the media row exists and belongs to a room of this category.
		// D1 has no transactions — SELECT-then-UPDATE has a race window if the pro
		// deletes the photo between the two statements. This single-statement form
		// is race-free and declarative.
		let result: { meta: { changes: number } };
		if (coverMediaId === null) {
			// Clearing the cover: always valid as long as the room_type exists.
			result = await db.run(sql`
				UPDATE room_types
				SET cover_media_id = NULL
				WHERE code = ${code}
			`);
		} else {
			// Setting the cover: validate media belongs to a room of this category.
			result = await db.run(sql`
				UPDATE room_types
				SET cover_media_id = ${coverMediaId}
				WHERE code = ${code}
				  AND ${coverMediaId} IN (
				    SELECT m.id FROM media m
				    JOIN rooms r ON m.room_id = r.id
				    WHERE r.room_type = ${code}
				      AND m.id = ${coverMediaId}
				  )
			`);
		}
 
		if (result.meta.changes === 0) {
			// Either: (a) room_type code doesn't exist, or (b) coverMediaId doesn't
			// belong to a room of this category (or the media was already deleted).
			return c.json(
				{
					success: false,
					error: { message: "media does not belong to a room of this category, or category does not exist" },
				},
				409,
			);
		}
 
		// Invalidate homepage + room-category cache (6B3).
		// Non-blocking: failures log + continue.
		try {
			const cache = createDualCache(c.env.KV_CACHE);
			const hour = new Date().getUTCHours();
			c.executionCtx.waitUntil(
				Promise.all([
					cache.delete(`${CACHE_KEYS.MARKETPLACE_HOMEPAGE}:h${hour}`),
					cache.delete(`${CACHE_KEYS.MARKETPLACE_ROOM_CATEGORIES}:h${hour}`),
					cache.delete(CACHE_KEYS.MARKETPLACE_HOMEPAGE),
					cache.delete(CACHE_KEYS.MARKETPLACE_ROOM_CATEGORIES),
				]).catch((err) => {
					logger.error("[admin/taxonomy.roomTypes.cover] cache invalidation failed", err);
				}),
			);
		} catch { /* executionCtx unavailable in tests */ }
 
		// Fetch and return the updated room_type row.
		const updated = await db
			.select()
			.from(schema.roomTypes)
			.where(eq(schema.roomTypes.code, code))
			.limit(1);
 
		return success(c, updated[0]);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// ============================================================================
// Room Category — list/single/media (D1B sort, photo picker)
// Defined BEFORE the generic /:type routes so Hono matches them first.
// Lane D's portal client (apps/portal/src/lib/api/admin/room-categories.ts)
// expects RoomCategoryWithStats shape on these endpoints.
// ============================================================================
 
type RoomCategoryWithStats = {
	code: string;
	label: string;
	sortOrder: number;
	coverMediaId: number | null;
	coverMediaUrl: string | null;
	coverMediaAlt: string | null;
	coverProjectTitle: string | null;
	coverProName: string | null;
	coverUploadedAt: string | null;
	coverSource: "curated" | "algorithmic" | "empty";
	projectCount: number;
	photoCount: number;
};
 
// Build enriched room-category stats. Single trip per category-set:
// - one query for the category rows (with cover_media_id)
// - one aggregate query for projectCount + photoCount per room_type
// - one batch fetch of cover media + parent project + parent pro
// Used by both the list and single endpoints below.
async function buildRoomCategoryStats(
	c: Context<Env>,
	codes: string[] | null,
): Promise<RoomCategoryWithStats[]> {
	const db = getDb(c.env.DB);
 
	// 1. Category rows.
	const categoryRows = codes
		? await db
				.select()
				.from(schema.roomTypes)
				.where(
					and(
						eq(schema.roomTypes.isActive, true),
						sql`${schema.roomTypes.code} IN (${sql.join(
							codes.map((c) => sql`${c}`),
							sql`, `,
						)})`,
					),
				)
				.orderBy(asc(schema.roomTypes.sortOrder), asc(schema.roomTypes.displayName))
		: await db
				.select()
				.from(schema.roomTypes)
				.where(eq(schema.roomTypes.isActive, true))
				.orderBy(asc(schema.roomTypes.sortOrder), asc(schema.roomTypes.displayName));
 
	if (categoryRows.length === 0) return [];
 
	// 2. Aggregate stats: distinct project count + media count per room_type.
	// Scoped to published projects so admin sees what visitors see.
	const statsRows = await db.all<{
		room_type: string;
		project_count: number;
		photo_count: number;
	}>(sql`
		SELECT
			r.room_type AS room_type,
			COUNT(DISTINCT p.id) AS project_count,
			COUNT(m.id) AS photo_count
		FROM rooms r
		JOIN projects p ON r.project_id = p.id
		LEFT JOIN media m ON m.room_id = r.id
		WHERE p.status = 'published'
		  AND r.room_type IN (${sql.join(
				categoryRows.map((row) => sql`${row.code}`),
				sql`, `,
			)})
		GROUP BY r.room_type
	`);
 
	const statsMap = new Map<string, { projectCount: number; photoCount: number }>();
	for (const row of statsRows) {
		statsMap.set(row.room_type, {
			projectCount: Number(row.project_count) || 0,
			photoCount: Number(row.photo_count) || 0,
		});
	}
 
	// 3. Cover-media enrichment for categories that have a curated cover.
	const coverMediaIds = categoryRows
		.map((r) => r.coverMediaId)
		.filter((id): id is number => id !== null);
 
	type CoverInfo = {
		id: number;
		storageKey: string;
		altText: string | null;
		dateCreated: Date | null;
		projectTitle: string | null;
		proName: string | null;
	};
	const coverMap = new Map<number, CoverInfo>();
	if (coverMediaIds.length > 0) {
		const coverRows = await db.all<{
			id: number;
			storage_key: string;
			alt_text: string | null;
			date_created: number | null;
			project_title: string | null;
			pro_name: string | null;
		}>(sql`
			SELECT
				m.id AS id,
				m.storage_key AS storage_key,
				m.alt_text AS alt_text,
				m.date_created AS date_created,
				p.title AS project_title,
				pr.business_name AS pro_name
			FROM media m
			JOIN rooms r ON m.room_id = r.id
			JOIN projects p ON r.project_id = p.id
			JOIN pros pr ON p.pro_id = pr.id
			WHERE m.id IN (${sql.join(
				coverMediaIds.map((id) => sql`${id}`),
				sql`, `,
			)})
		`);
		for (const row of coverRows) {
			coverMap.set(Number(row.id), {
				id: Number(row.id),
				storageKey: row.storage_key,
				altText: row.alt_text,
				dateCreated: row.date_created
					? new Date(Number(row.date_created) * 1000)
					: null,
				projectTitle: row.project_title,
				proName: row.pro_name,
			});
		}
	}
 
	// 4. Assemble.
	return categoryRows.map((row) => {
		const stats = statsMap.get(row.code) ?? { projectCount: 0, photoCount: 0 };
		const cover = row.coverMediaId !== null ? coverMap.get(row.coverMediaId) ?? null : null;
		const coverSource: RoomCategoryWithStats["coverSource"] =
			cover !== null
				? "curated"
				: stats.photoCount > 0
					? "algorithmic"
					: "empty";
		return {
			code: row.code,
			label: row.displayName,
			sortOrder: row.sortOrder,
			coverMediaId: row.coverMediaId ?? null,
			coverMediaUrl: cover ? `/api/images/${cover.storageKey}` : null,
			coverMediaAlt: cover?.altText ?? null,
			coverProjectTitle: cover?.projectTitle ?? null,
			coverProName: cover?.proName ?? null,
			coverUploadedAt: cover?.dateCreated?.toISOString() ?? null,
			coverSource,
			projectCount: stats.projectCount,
			photoCount: stats.photoCount,
		};
	});
}
 
// List all room categories with stats. Lane D's room-categories list page calls
// this with ?withStats=true. Sort order is D1B (needs-attention-first) applied
// client-side in Lane D — server returns taxonomy sortOrder.
taxonomy.get("/roomTypes/list-with-stats", async (c) => {
	try {
		const stats = await buildRoomCategoryStats(c, null);
		return success(c, stats);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Single room category with stats. Lane D's detail page calls this.
taxonomy.get("/roomTypes/:code/with-stats", async (c) => {
	try {
		const code = c.req.param("code");
		const rows = await buildRoomCategoryStats(c, [code]);
		if (rows.length === 0) {
			return c.json(
				{ success: false, error: { message: "room type not found" } },
				404,
			);
		}
		return success(c, rows[0]);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Photo picker: list media available for a room category. Used by the
// /admin/room-categories/:code detail page (Lane D).
// Sorted by upload date (recent) or media id (popular placeholder until a
// real popularity signal exists).
taxonomy.get("/roomTypes/:code/media", async (c) => {
	try {
		const code = c.req.param("code");
		const limit = Math.min(
			Math.max(1, Number(c.req.query("limit")) || 100),
			500,
		);
		const sortBy = c.req.query("sortBy") === "popular" ? "popular" : "recent";
		const db = getDb(c.env.DB);
 
		// All media from rooms of this type in published projects.
		// Returns RoomCategoryMedia[] (Lane D client type).
		const rows = await db.all<{
			id: number;
			storage_key: string;
			alt_text: string | null;
			pro_name: string;
			pro_business_name: string;
			project_title: string;
			project_id: string;
			date_created: number;
		}>(sql`
			SELECT
				m.id AS id,
				m.storage_key AS storage_key,
				m.alt_text AS alt_text,
				pr.business_name AS pro_name,
				pr.business_name AS pro_business_name,
				p.title AS project_title,
				p.id AS project_id,
				m.date_created AS date_created
			FROM media m
			JOIN rooms r ON m.room_id = r.id
			JOIN projects p ON r.project_id = p.id
			JOIN pros pr ON p.pro_id = pr.id
			WHERE r.room_type = ${code}
			  AND p.status = 'published'
			  AND m.media_type = 'image'
			ORDER BY ${sortBy === "popular" ? sql`m.id DESC` : sql`m.date_created DESC`}
			LIMIT ${limit}
		`);
 
		const media = rows.map((row) => ({
			id: Number(row.id),
			url: `/api/images/${row.storage_key}`,
			altText: row.alt_text,
			proName: row.pro_name,
			proBusinessName: row.pro_business_name,
			projectTitle: row.project_title,
			projectId: row.project_id,
			uploadedAt: row.date_created
				? new Date(Number(row.date_created) * 1000).toISOString()
				: new Date(0).toISOString(),
			viewCount: 0, // Placeholder — wire up real viewCount when media-level analytics exist.
		}));
 
		return success(c, media);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// ============================================================================
// Generic CRUD Handlers
// ============================================================================
 
// List all items for a taxonomy type
taxonomy.get("/:type", async (c) => {
	try {
		const type = c.req.param("type");
		validateTaxonomyType(type);
 
		const db = getDb(c.env.DB);
		const strategy = getStrategyForType(type);
		const table = strategy.getTable();
		const nameField = strategy.getNameField();
 
		// Get query parameters for filtering
		const isActiveParam = c.req.query("isActive");
		const includeInactive = c.req.query("includeInactive") === "true";
 
		// Build the query based on isActive filter
		let items: (typeof table.$inferSelect)[];
		if (!includeInactive && isActiveParam !== "false") {
			items = await db
				.select()
				.from(table)
				.where(eq(table.isActive, true))
				.orderBy(asc(table.sortOrder), asc(nameField));
		} else if (isActiveParam === "false") {
			items = await db
				.select()
				.from(table)
				.where(eq(table.isActive, false))
				.orderBy(asc(table.sortOrder), asc(nameField));
		} else {
			items = await db
				.select()
				.from(table)
				.orderBy(asc(table.sortOrder), asc(nameField));
		}
 
		// Transform items using strategy (adds id/name for roomTypes, no-op for standard types)
		const transformed = items.map((item) => strategy.transformItem(item));
 
		return success(c, transformed);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Get single item by ID
taxonomy.get("/:type/:id", async (c) => {
	try {
		const type = c.req.param("type");
		const id = c.req.param("id");
		validateTaxonomyType(type);
 
		const db = getDb(c.env.DB);
		const strategy = getStrategyForType(type);
		const table = strategy.getTable();
 
		const items = await db
			.select()
			.from(table)
			.where(strategy.buildFindByIdQuery(id))
			.limit(1);
 
		const item = items[0];
		if (!item) {
			throw new NotFoundError(type, id);
		}
 
		return success(c, strategy.transformItem(item));
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Create new item
taxonomy.post("/:type", async (c) => {
	try {
		const type = c.req.param("type");
		validateTaxonomyType(type);
 
		requireUser(c.get("user"));
		const body = await c.req.json<Record<string, unknown>>();
 
		// Validate required fields
		validateRequiredFields(type, body);
		validateEnumFields(type, body);
 
		const db = getDb(c.env.DB);
		const strategy = getStrategyForType(type);
		const table = strategy.getTable();
 
		// Prepare data using strategy (handles ID generation for standard types, code for roomTypes)
		const data = strategy.prepareInsertData(body);
 
		// Insert the new item
		const result = await db
			.insert(table)
			.values(data as never)
			.returning();
 
		// Transform for response (adds id/name for roomTypes, no-op for standard types)
		const item = result[0];
		return success(c, strategy.transformItem(item), 201);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Update item
taxonomy.put("/:type/:id", async (c) => {
	try {
		const type = c.req.param("type");
		const id = c.req.param("id");
		validateTaxonomyType(type);
 
		requireUser(c.get("user"));
		const body = await c.req.json<Record<string, unknown>>();
 
		// Validate enum fields if they're being updated
		validateEnumFields(type, body);
 
		const db = getDb(c.env.DB);
		const strategy = getStrategyForType(type);
		const table = strategy.getTable();
 
		// Check if item exists
		const existing = await db
			.select()
			.from(table)
			.where(strategy.buildFindByIdQuery(id))
			.limit(1);
 
		if (!existing[0]) {
			throw new NotFoundError(type, id);
		}
 
		// Prepare update data using strategy (removes primary key fields)
		const updateData = strategy.prepareUpdateData(body);
 
		// Update the item
		const result = await db
			.update(table)
			.set(updateData as never)
			.where(strategy.buildFindByIdQuery(id))
			.returning();
 
		// Transform for response (adds id/name for roomTypes, no-op for standard types)
		const item = result[0];
		return success(c, strategy.transformItem(item));
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Soft delete (set isActive = false)
taxonomy.delete("/:type/:id", async (c) => {
	try {
		const type = c.req.param("type");
		const id = c.req.param("id");
		validateTaxonomyType(type);
 
		requireUser(c.get("user"));
		const db = getDb(c.env.DB);
		const strategy = getStrategyForType(type);
		const table = strategy.getTable();
 
		// Check if item exists
		const existing = await db
			.select()
			.from(table)
			.where(strategy.buildFindByIdQuery(id))
			.limit(1);
 
		if (!existing[0]) {
			throw new NotFoundError(type, id);
		}
 
		// Soft delete by setting isActive to false
		const result = await db
			.update(table)
			.set({ isActive: false } as never)
			.where(strategy.buildFindByIdQuery(id))
			.returning();
 
		const item = result[0];
		return success(c, {
			message: `${type} item deleted successfully`,
			item: strategy.transformItem(item),
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Reorder items (update sort_order for multiple items)
taxonomy.patch("/:type/reorder", async (c) => {
	try {
		const type = c.req.param("type");
		validateTaxonomyType(type);
 
		requireUser(c.get("user"));
		const body = await c.req.json<{
			items: Array<{ id: string; sortOrder: number }>;
		}>();
 
		if (!body.items || !Array.isArray(body.items)) {
			throw new ValidationError("Request body must contain an 'items' array");
		}
 
		const db = getDb(c.env.DB);
		const strategy = getStrategyForType(type);
		const table = strategy.getTable();
 
		// Update each item's sortOrder using strategy to handle primary key differences
		const updatePromises = body.items.map((item) => {
			const { condition, data } = strategy.buildReorderUpdate(
				item.id,
				item.sortOrder,
			);
			return db
				.update(table)
				.set(data as never)
				.where(condition);
		});
		await Promise.all(updatePromises);
 
		return success(c, {
			message: `Reordered ${body.items.length} items successfully`,
			count: body.items.length,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default taxonomy;