import { getUserByUsername, updateUser, uploadProfileImage } from "https://esm.town/v/iamseeley/Queries";
import EditProfilePage from "https://esm.town/v/iamseeley/EditProfilePage";
import RootLayout from "https://esm.town/v/iamseeley/RootLayout";
export const getUserProfileHandler = async (c) => {
const username = c.req.param('username');
const payload = await c.get('jwtPayload');
if (payload.username !== username) {
return c.html(
<RootLayout>
<p>You are not authorized to access this profile.</p>
</RootLayout>
);
}
try {
const user = await getUserByUsername(username);
return c.html(<EditProfilePage user={user} />);
} catch (error) {
console.error("Error fetching user:", error);
return c.html(
<RootLayout>
<p>Error loading profile.</p>
</RootLayout>
);
}
};
export const updateUserProfileHandler = async (c) => {
try {
const body = await c.req.parseBody();
const username = c.req.param("username");
const name = body.name;
const bio = body.bio;
const city = body.city;
const currentlyListening = body.currentlyListening;
const currentlyReading = {
title: body.currentlyReadingTitle,
author: body.currentlyReadingAuthor,
coverImage: body.currentlyReadingCoverImage,
};
const currentlyWatching = {
title: body.currentlyWatchingTitle,
platform: body.currentlyWatchingPlatform,
posterImage: body.currentlyWatchingPosterImage,
};
const profile_theme = body.profile_theme;
if (typeof name !== "string" || typeof bio !== "string") {
throw new Error("name and bio must be strings.");
}
const existingUser = await getUserByUsername(username);
const profileImgFile = body.profile_img;
let profileImgUrl = existingUser.profile_img;
if (profileImgFile && profileImgFile.size) {
profileImgUrl = await uploadProfileImage(profileImgFile, username);
}
await updateUser(existingUser.id, name, bio, city, currentlyListening, currentlyReading, currentlyWatching, profile_theme, profileImgUrl);
const updatedUser = await getUserByUsername(username);
return c.html(<EditProfilePage user={updatedUser} />);
} catch (error) {
console.error("Error updating profile:", error);
return c.html(
<RootLayout>
<p>Error updating profile.</p>
</RootLayout>
);
}
};