import { ContentfulStatusCode } from "hono/utils/http-status";
import { z } from "zod";
import { apiResponse } from "../../../modules/api-utils/apiResponse";
import { createRoute } from "../../../modules/api-utils/createRoute";
import { authMiddleware } from "../../middleware/authorization";

const updateSchema = z
  .object({
    name: z.string().optional(),
    firstName: z.string().nullable().optional(),
    lastName: z.string().nullable().optional(),
    image: z.string().optional(),
  })
  .strict();

export default createRoute(
  "patch",
  ["/@me"],
  async (c) => {
    const body = updateSchema.parse(await c.req.json());
    const updatedUser = await c.get("user")?.update(body);
    const response = apiResponse.successful(
      "Successfully updated user.",
      updatedUser?.toJson()
    );

    return c.json(response, response.status as ContentfulStatusCode);
  },
  authMiddleware({ scopes: ["user.write"] })
);
