import { Router } from "express";
import type { Request } from "express";
import { graphqlClient } from "../lib/graphqlClient";
import { respondWithError } from "../lib/error";
import {
  GetUserProfileDocument,
  UpdateUserProfileDocument,
} from "../../shared/generated/graphql";

interface GqlRequest extends Request {
  gql?: typeof graphqlClient;
}

const router = Router();

// GET /api/userProfile/:userId
router.get("/:userId", async (req: GqlRequest, res) => {
  try {
    const client = req.gql || graphqlClient;
    const { userProfile } = await client.request(GetUserProfileDocument, {
      userId: req.params.userId,
    });
    if (!userProfile)
      return res.status(404).json({ message: "UserProfile not found" });
    res.json(userProfile);
  } catch (error) {
    respondWithError(res, error, "Failed to fetch user profile");
  }
});

// PUT /api/userProfile/:userId
router.put("/:userId", async (req: GqlRequest, res) => {
  try {
    const client = req.gql || graphqlClient;
    const { updateUserProfile } = await client.request(
      UpdateUserProfileDocument,
      {
        userId: req.params.userId,
        input: req.body,
      }
    );
    res.json(updateUserProfile);
  } catch (error) {
    respondWithError(res, error, "Failed to update user profile");
  }
});

export default router;
