import { Hono } from "hono";
import { parseId } from "../lib/params.ts";
import { getPublicProfile } from "../services/profile.service.ts";
import { getImageUrl } from "../services/storage.service.ts";

type Env = { Variables: { db?: any; userId?: number } };

async function enrichAvatarUrl<T extends { avatarUrl: string | null }>(
	record: T,
): Promise<T & { avatarImageUrl: string | null }> {
	return {
		...record,
		avatarImageUrl: record.avatarUrl
			? await getImageUrl(record.avatarUrl)
			: null,
	};
}

const app = new Hono<Env>();

// GET /:id/profile — Public profile (no auth required)
app.get("/:id/profile", async (c) => {
	const db = c.get("db");
	const id = parseId(c.req.param("id"));
	if (!id) return c.json({ error: "Invalid user ID" }, 400);

	const profile = await getPublicProfile(db, id);
	if (!profile) return c.json({ error: "User not found" }, 404);

	return c.json(await enrichAvatarUrl(profile));
});

export { app as profileRoutes };
