All files / routes/admin/blogs index.ts

94.53% Statements 242/256
99.28% Branches 138/139
100% Functions 24/24
94.48% Lines 240/254

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 730 731 732 733 734 735 736 737 738 739 740 741 742 743                                                                            18x 18x 2x       2x             2x 14x 14x 14x 14x       14x 14x   14x 1x 1x   13x     14x                         14x 14x           13x     6x 6x     13x 13x 3x 3x   3x 3x 2x         13x             13x           1x         2x 4x 4x 4x 4x   4x 1x     3x 3x   1x         2x 3x 3x 3x   2x 1x       1x           1x             2x         2x 20x 20x 20x 20x     18x 4x           14x     14x     20x 13x 2x           11x 11x                                               9x 1x   2x       9x 1x 1x                       9x         1x 2x                 9x   9x   11x         2x 20x 20x 20x 20x 20x     20x     20x 19x 2x       17x 4x       16x 2x                     14x                                         13x 3x     3x 2x 2x               13x 3x     3x 2x 1x                         13x 3x     3x 2x 2x 2x                   13x   13x   7x         2x 3x 3x 3x   2x 1x     1x   2x         2x 8x 8x 8x     8x 8x 1x   7x 1x         6x   5x 1x           4x 2x         2x 1x                 1x             4x 4x         4x 4x   4x 4x                       4x                                                             4x   4x         2x 3x 3x 3x   2x 1x     1x   2x         2x 4x 4x 4x 4x   4x 4x 1x     3x 3x 3x   3x 1x     2x           4x   4x 2x       2x 2x         2x   2x                 2x 8x 8x 8x 8x     8x 2x           6x 5x 1x       4x 4x 1x     3x                   3x 3x   1x 1x                                             3x   5x         2x 4x 4x 4x 4x     4x 3x 1x     2x 2x 1x     1x   3x                 2x 6x 6x 6x 6x     6x 1x       5x 4x 1x       3x 3x 1x     2x             2x   4x         2x 5x 5x 5x 5x     5x 4x   4x 2x     2x 2x 1x     1x   4x               2x 2x 2x 2x      
// Admin Blog Routes - Main CRUD + barrel for sub-routers
import { Hono } from "hono";
import { eq } from "drizzle-orm";
import * as schema from "../../../db/schema";
import { purgeEdgeCache } from "../../../lib/edge-cache";
import type { Dal } from "../../../dal";
import type { Services } from "../../../services";
import {
	success,
	successWithPagination,
	handleError,
} from "../../../lib/response";
import {
	buildPaginationMeta,
	requireUser,
	generateId,
	generateSlug,
} from "../../../lib/utils";
import { validateUploadedFile } from "../../../lib/file-validation";
import { ValidationError, NotFoundError } from "../../../lib/errors";
import { checkBlogWordLimit } from "@interioring/utils/validation/blog";
import categoriesRoutes from "./categories.routes";
import tagsRoutes from "./tags.routes";
import suggestionsRoutes from "./suggestions.routes";
import editorialRoutes from "./editorial.routes";
import { logger } from "../../../lib/logger";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
	};
};
 
function assertBlogWordLimit(content: string) {
	const result = checkBlogWordLimit(content);
	if (!result.withinLimit) {
		throw new ValidationError(result.message ?? "Blog content exceeds the word limit.");
	}
}
 
const blogs = new Hono<Env>();
 
// ============================================================================
// BLOGS
// ============================================================================
 
// List all blogs with filters and pagination
blogs.get("/", async (c) => {
	try {
		const dal = c.get("dal");
		const limitParam = Number(c.req.query("limit") || 20);
		const safeLimit = Math.min(100, Math.max(1, limitParam));
 
		// Support both page-based and offset-based pagination
		let page: number;
		const offsetParam = c.req.query("offset");
		const pageParam = c.req.query("page");
 
		if (offsetParam !== undefined) {
			const offset = Math.max(0, Number(offsetParam));
			page = Math.floor(offset / safeLimit) + 1;
		} else {
			page = Math.max(1, Number(pageParam || 1));
		}
 
		const filters = {
			status: c.req.query("status")
				? c.req.query("status")?.split(",")
				: undefined,
			blogType: c.req.query("blogType"),
			categoryId: c.req.query("categoryId"),
			cityId: c.req.query("cityId"),
			ideaSource: c.req.query("ideaSource"),
			ideaSourceProId: c.req.query("ideaSourceProId"),
			createdBy: c.req.query("createdBy"),
			search: c.req.query("search"),
		};
 
		const offset = (page - 1) * safeLimit;
		const [data, total] = await Promise.all([
			dal.blogs.findAll(filters, offset, safeLimit),
			dal.blogs.count(filters),
		]);
 
		// Resolve pro names for blogs with ideaSourceProId
		const proIds = [
			...new Set(
				data
					.map((b) => b.ideaSourceProId)
					.filter((id): id is string => !!id),
			),
		];
		const proNameMap: Record<string, string> = {};
		if (proIds.length > 0) {
			const pros = await Promise.all(
				proIds.map((id) => dal.pros.findById(id)),
			);
			for (const pro of pros) {
				if (pro) {
					proNameMap[pro.id] = pro.businessName;
				}
			}
		}
 
		const enriched = data.map((blog) => ({
			...blog,
			ideaSourceProName: blog.ideaSourceProId
				? proNameMap[blog.ideaSourceProId] || null
				: null,
		}));
 
		return successWithPagination(
			c,
			enriched,
			buildPaginationMeta(total, page, safeLimit),
		);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Check blog slug availability
blogs.get("/check-slug", async (c) => {
	try {
		const dal = c.get("dal");
		const slug = c.req.query("slug");
		const excludeId = c.req.query("excludeId");
 
		if (!slug) {
			throw new ValidationError("slug query parameter is required");
		}
 
		const exists = await dal.blogs.slugExists(slug, excludeId || undefined);
		return success(c, { available: !exists });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Get single blog by ID
blogs.get("/:id", async (c) => {
	try {
		const dal = c.get("dal");
		const blog = await dal.blogs.findById(c.req.param("id"));
 
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		// Also fetch related data
		const [tags, pros, projects] = await Promise.all([
			dal.blogTags.findByBlogId(blog.id),
			dal.blogPros.findAll({ blogId: blog.id }),
			dal.blogProjects.findByBlogId(blog.id),
		]);
 
		return success(c, {
			...blog,
			tags,
			pros,
			projects,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Create new blog
blogs.post("/", async (c) => {
	try {
		const dal = c.get("dal");
		const user = requireUser(c.get("user"));
		const body = await c.req.json();
 
		// Validate required fields
		if (!body.title || !body.content || !body.blogType || !body.ideaSource) {
			throw new ValidationError(
				"Missing required fields: title, content, blogType, ideaSource",
			);
		}
 
		// Validate word limit
		assertBlogWordLimit(body.content);
 
		// Generate slug from title if not provided
		const slug = body.slug || generateSlug(body.title);
 
		// Check if slug already exists
		const slugExists = await dal.blogs.slugExists(slug);
		if (slugExists) {
			throw new ValidationError(
				`Slug "${slug}" already exists. Please provide a unique slug.`,
			);
		}
 
		// Create blog + relationships sequentially (D1 doesn't support transactions)
		const blogId = generateId();
		const [blog] = await dal.db
			.insert(schema.blogs)
			.values({
				id: blogId,
				slug,
				title: body.title,
				metaDescription: body.metaDescription || null,
				content: body.content,
				featuredImageUrl: body.featuredImageUrl || null,
				featuredImageAlt: body.featuredImageAlt || null,
				status: body.status || "draft",
				blogType: body.blogType,
				primaryKeyword: body.primaryKeyword || null,
				secondaryKeywords: body.secondaryKeywords || null,
				categoryId: body.categoryId || null,
				cityId: body.cityId || null,
				ideaSource: body.ideaSource,
				ideaSourceProId: body.ideaSourceProId || null,
				readTimeMinutes: body.readTimeMinutes || null,
				createdBy: user.id,
			})
			.returning();
 
		// Add tags — bulk insert (one DB roundtrip; statement-level atomic)
		if (body.tagIds && Array.isArray(body.tagIds) && body.tagIds.length > 0) {
			await dal.db
				.insert(schema.blogTagAssignments)
				.values(body.tagIds.map((tagId: string) => ({ blogId, tagId })));
		}
 
		// Add pros — bulk insert
		if (body.proIds && Array.isArray(body.proIds) && body.proIds.length > 0) {
			await dal.db.insert(schema.blogPros).values(
				body.proIds.map((proId: string) => ({
					id: generateId(),
					blogId,
					proId,
					attributionType: "project_feature" as const,
					approvalStatus: "pending" as const,
					approvalRequestedAt: new Date(),
				})),
			);
		}
 
		// Add projects — bulk insert
		if (
			body.projectIds &&
			Array.isArray(body.projectIds) &&
			body.projectIds.length > 0
		) {
			await dal.db.insert(schema.blogProjects).values(
				body.projectIds.map((projectId: string, index: number) => ({
					id: generateId(),
					blogId,
					projectId,
					displayOrder: index,
				})),
			);
		}
 
		logger.info(`[Blog Create] Created blog ${blog.id} with relationships`);
 
		return success(c, blog, 201);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Update blog
blogs.put("/:id", async (c) => {
	try {
		const dal = c.get("dal");
		const user = c.get("user");
		const body = await c.req.json();
		const id = c.req.param("id");
 
		// Verify user is authenticated (consistency with create route)
		requireUser(user);
 
		// Check if blog exists
		const existing = await dal.blogs.findById(id);
		if (!existing) {
			throw new NotFoundError("Blog not found");
		}
 
		// Validate word limit
		if (body.content) {
			assertBlogWordLimit(body.content);
		}
 
		// If slug is being changed, check for uniqueness
		if (body.slug && body.slug !== existing.slug) {
			const slugExists = await dal.blogs.slugExists(body.slug, id);
			/* v8 ignore start -- defensive guard: slug collision unlikely in tests */
			if (slugExists) {
				throw new ValidationError(
					`Slug "${body.slug}" already exists. Please provide a unique slug.`,
				);
			}
			/* v8 ignore stop */
		}
 
		// Update blog (D1 doesn't support transactions — use sequential operations)
		const [blog] = await dal.db
			.update(schema.blogs)
			.set({
				slug: body.slug,
				title: body.title,
				metaDescription: body.metaDescription,
				content: body.content,
				featuredImageUrl: body.featuredImageUrl,
				featuredImageAlt: body.featuredImageAlt,
				status: body.status,
				blogType: body.blogType,
				primaryKeyword: body.primaryKeyword,
				secondaryKeywords: body.secondaryKeywords,
				categoryId: body.categoryId,
				cityId: body.cityId,
				readTimeMinutes: body.readTimeMinutes,
			})
			.where(eq(schema.blogs.id, id))
			.returning();
 
		// Replace tags if provided
		if (body.tagIds !== undefined) {
			await dal.db
				.delete(schema.blogTagAssignments)
				.where(eq(schema.blogTagAssignments.blogId, id));
			if (Array.isArray(body.tagIds)) {
				for (const tagId of body.tagIds) {
					await dal.db
						.insert(schema.blogTagAssignments)
						.values({ blogId: id, tagId });
				}
			}
		}
 
		// Replace pros if provided
		if (body.proIds !== undefined) {
			await dal.db
				.delete(schema.blogPros)
				.where(eq(schema.blogPros.blogId, id));
			if (Array.isArray(body.proIds)) {
				for (const proId of body.proIds) {
					await dal.db.insert(schema.blogPros).values({
						id: generateId(),
						blogId: id,
						proId,
						attributionType: "project_feature",
						approvalStatus: "pending",
						approvalRequestedAt: new Date(),
					});
				}
			}
		}
 
		// Replace projects if provided
		if (body.projectIds !== undefined) {
			await dal.db
				.delete(schema.blogProjects)
				.where(eq(schema.blogProjects.blogId, id));
			if (Array.isArray(body.projectIds)) {
				let displayOrder = 0;
				for (const projectId of body.projectIds) {
					await dal.db.insert(schema.blogProjects).values({
						id: generateId(),
						blogId: id,
						projectId,
						displayOrder: displayOrder++,
					});
				}
			}
		}
 
		logger.info(`[Blog Update] Updated blog ${id} with relationships`);
 
		return success(c, blog);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Delete blog
blogs.delete("/:id", async (c) => {
	try {
		const dal = c.get("dal");
		const deleted = await dal.blogs.delete(c.req.param("id"));
 
		if (!deleted) {
			throw new NotFoundError("Blog not found");
		}
 
		return success(c, { message: "Blog deleted successfully" });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Publish blog
blogs.post("/:id/publish", async (c) => {
	try {
		const dal = c.get("dal");
		const id = c.req.param("id");
 
		// Validate cover image before publishing
		const existing = await dal.blogs.findById(id);
		if (!existing) {
			throw new NotFoundError("Blog not found");
		}
		if (!existing.featuredImageUrl) {
			throw new ValidationError(
				"A cover image is required to publish. Please add a cover image first.",
			);
		}
 
		const blog = await dal.blogs.publish(id);
 
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		// Auto-add author attribution for the pro if the blog is associated
		// with a pro (ideaSourceProId) and no author entry exists yet.
		// This ensures the pro is always credited as author, not the admin.
		if (existing.ideaSourceProId) {
			const existingAuthors = await dal.blogPros.findAll({
				blogId: id,
				proId: existing.ideaSourceProId,
				attributionType: "author",
			});
			if (existingAuthors.length === 0) {
				await dal.blogPros.create({
					id: generateId(),
					blogId: id,
					proId: existing.ideaSourceProId,
					attributionType: "author",
					approvalStatus: "approved",
					approvalRequestedAt: new Date(),
					approvedAt: new Date(),
				});
				logger.info(
					`[Blog Publish] Auto-added author attribution for pro ${existing.ideaSourceProId} on blog ${id}`,
				);
			}
		}
 
		// Purge edge cache so the new blog appears in marketplace immediately
		try {
			c.executionCtx.waitUntil(
				purgeEdgeCache(`${c.env.BETTER_AUTH_URL}/api/marketplace/blogs`),
			);
		} catch { /* executionCtx unavailable in tests */ }
 
		try {
			c.executionCtx.waitUntil(
				(async () => {
					try {
					const { CommunicationGateway } = await import(
						"../../../lib/communication/gateway"
					);
					const { BlogLifecycleHandler } = await import(
						"../../../lib/communication/handlers/blog-lifecycle.handler"
					);
					const gateway = new CommunicationGateway(dal, c.env);
					const handler = new BlogLifecycleHandler(gateway, dal);
					const blogProsMap = await dal.blogPros.findByBlogIds([id]);
					/* v8 ignore start -- V8 artifact: ?? fallback */
					const blogPros = blogProsMap.get(id) ?? [];
					/* v8 ignore stop */
					for (const bp of blogPros) {
						await handler.handlePublished({
							proId: bp.proId,
							blogId: id,
							blogTitle: blog.title,
						});
						try {
							await c.get("services").notification.notify({
								proId: bp.proId,
								eventType: "blog_published",
								title: "Your blog post has been published!",
								body: `"${blog.title}" is now live on the marketplace`,
								data: { url: `/blogs`, blogId: id },
							});
						} catch (notifErr) {
							logger.error(
								"[BLOG] Failed to send push notification:",
								notifErr,
							);
						}
					}
				} catch (err) {
					logger.error(
						"[BLOG] Failed to send published notification:",
						err,
					);
				}
			})(),
		);
		} catch { /* executionCtx unavailable in tests */ }
 
		return success(c, blog);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Unpublish blog
blogs.post("/:id/unpublish", async (c) => {
	try {
		const dal = c.get("dal");
		const blog = await dal.blogs.unpublish(c.req.param("id"));
 
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		return success(c, blog);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Upload cover image for blog (admin)
blogs.post("/:id/upload-cover", async (c) => {
	try {
		const dal = c.get("dal");
		const r2 = c.env.R2;
		const blogId = c.req.param("id");
 
		const blog = await dal.blogs.findById(blogId);
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		const formData = await c.req.formData();
		const file = formData.get("file") as File | null;
		const altText = formData.get("altText") as string | null;
 
		if (!file) {
			throw new ValidationError("No file provided");
		}
 
		validateUploadedFile(file);
 
		// Store under admin path since there may be no associated pro
		/* v8 ignore start -- V8 artifact: || fallback */
		const ext = file.name.split(".").pop() || "jpg";
		/* v8 ignore stop */
		const filename = `admin/blogs/${blogId}/cover-${generateId()}.${ext}`;
 
		const arrayBuffer = await file.arrayBuffer();
		await r2.put(filename, arrayBuffer, {
			httpMetadata: { contentType: file.type },
		});
 
		const imageUrl = `/api/images/${filename}`;
		const updated = await dal.blogs.update(blogId, {
			featuredImageUrl: imageUrl,
			featuredImageAlt: altText || null,
		});
 
		return success(c, { blog: updated, imageUrl });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// ============================================================================
// BLOG PROS
// ============================================================================
 
// Add pro to blog
blogs.post("/:id/pros", async (c) => {
	try {
		const dal = c.get("dal");
		const body = await c.req.json();
		const blogId = c.req.param("id");
 
		// Validate required fields
		if (!body.proId || !body.attributionType) {
			throw new ValidationError(
				"Missing required fields: proId, attributionType",
			);
		}
 
		// Check if blog exists
		const blog = await dal.blogs.findById(blogId);
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		// Check if pro exists
		const pro = await dal.pros.findById(body.proId);
		if (!pro) {
			throw new NotFoundError("Pro not found");
		}
 
		const blogPro = await dal.blogPros.create({
			id: generateId(),
			blogId,
			proId: body.proId,
			attributionType: body.attributionType,
			approvalStatus: body.approvalStatus || "pending",
			approvalRequestedAt:
				body.approvalStatus === "pending" ? new Date() : null,
		});
 
		try {
			c.executionCtx.waitUntil(
				(async () => {
					try {
						const { CommunicationGateway } = await import(
							"../../../lib/communication/gateway"
						);
						const { BlogLifecycleHandler } = await import(
							"../../../lib/communication/handlers/blog-lifecycle.handler"
						);
						const gateway = new CommunicationGateway(dal, c.env);
						const handler = new BlogLifecycleHandler(gateway, dal);
						await handler.handleApprovalRequest({
							proId: body.proId,
							blogId,
							blogTitle: blog.title,
						});
					} catch (err) {
						logger.error(
							"[BLOG] Failed to send approval request notification:",
							err,
						);
					}
				})(),
			);
		} catch { /* executionCtx unavailable in tests */ }
 
		return success(c, blogPro, 201);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Remove pro from blog
blogs.delete("/:id/pros/:proId", async (c) => {
	try {
		const dal = c.get("dal");
		const blogId = c.req.param("id");
		const proId = c.req.param("proId");
 
		// Find the blog pro association
		const blogPros = await dal.blogPros.findAll({ blogId, proId });
		if (blogPros.length === 0) {
			throw new NotFoundError("Blog pro association not found");
		}
 
		const deleted = await dal.blogPros.delete(blogPros[0].id);
		if (!deleted) {
			throw new NotFoundError("Blog pro association not found");
		}
 
		return success(c, { message: "Pro removed from blog successfully" });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// ============================================================================
// BLOG PROJECTS
// ============================================================================
 
// Add project to blog
blogs.post("/:id/projects", async (c) => {
	try {
		const dal = c.get("dal");
		const body = await c.req.json();
		const blogId = c.req.param("id");
 
		// Validate required fields
		if (!body.projectId) {
			throw new ValidationError("Missing required field: projectId");
		}
 
		// Check if blog exists
		const blog = await dal.blogs.findById(blogId);
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		// Check if project exists
		const project = await dal.projects.findById(body.projectId);
		if (!project) {
			throw new NotFoundError("Project not found");
		}
 
		const blogProject = await dal.blogProjects.create({
			id: generateId(),
			blogId,
			projectId: body.projectId,
			displayOrder: body.displayOrder ?? 0,
		});
 
		return success(c, blogProject, 201);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Remove project from blog
blogs.delete("/:id/projects/:projectId", async (c) => {
	try {
		const dal = c.get("dal");
		const blogId = c.req.param("id");
		const projectId = c.req.param("projectId");
 
		// Find the blog project association
		const blogProjects = await dal.blogProjects.findByBlogId(blogId);
		const blogProject = blogProjects.find((bp) => bp.projectId === projectId);
 
		if (!blogProject) {
			throw new NotFoundError("Blog project association not found");
		}
 
		const deleted = await dal.blogProjects.delete(blogProject.id);
		if (!deleted) {
			throw new NotFoundError("Blog project association not found");
		}
 
		return success(c, { message: "Project removed from blog successfully" });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// ============================================================================
// SUB-ROUTERS
// ============================================================================
 
blogs.route("/categories", categoriesRoutes);
blogs.route("/tags", tagsRoutes);
blogs.route("/suggestions", suggestionsRoutes);
blogs.route("/editorial", editorialRoutes);
 
export default blogs;