From 9c9f625c539248f99671a1127cb3ec353fd7fd6d Mon Sep 17 00:00:00 2001
From: Stuart Long Chay Boon <chayboon@gmail.com>
Date: Fri, 14 Oct 2022 02:14:29 +0800
Subject: [PATCH] [offers][feat] add add to user profile endpoint

---
 .../src/pages/offers/test/createProfile.tsx   | 20 ++++++++++
 .../router/offers/offers-profile-router.ts    | 38 +++++++++++++++++++
 2 files changed, 58 insertions(+)

diff --git a/apps/portal/src/pages/offers/test/createProfile.tsx b/apps/portal/src/pages/offers/test/createProfile.tsx
index 5b42a76f..67897015 100644
--- a/apps/portal/src/pages/offers/test/createProfile.tsx
+++ b/apps/portal/src/pages/offers/test/createProfile.tsx
@@ -25,6 +25,23 @@ function Test() {
     },
   });
 
+  const addToUserProfileMutation = trpc.useMutation(['offers.profile.addToUserProfile'], {
+    onError(err: any) {
+      alert(err);
+    },
+    onSuccess(data) {
+      setCreatedData(JSON.stringify(data));
+    },
+  })
+
+  const handleLink = () => {
+    addToUserProfileMutation.mutate({
+      profileId: 'cl96stky5002ew32gx2kale2x',
+      token: 'afca11e436d21bde24543718fa957c6c625335439dc504f24ee35eae7b5ef1ba',
+      userId: 'cl97dl51k001e7iygd5v5gt58'
+    })
+  }
+
   const handleClick = () => {
     createMutation.mutate({
       background: {
@@ -525,6 +542,9 @@ function Test() {
       <button type="button" onClick={handleUpdate}>
         UPDATE!
       </button>
+      <button type="button" onClick={handleLink}>
+        LINKKKK!
+      </button>
       <button
         className="text-danger-600"
         type="button"
diff --git a/apps/portal/src/server/router/offers/offers-profile-router.ts b/apps/portal/src/server/router/offers/offers-profile-router.ts
index 04a449ff..944cc3e0 100644
--- a/apps/portal/src/server/router/offers/offers-profile-router.ts
+++ b/apps/portal/src/server/router/offers/offers-profile-router.ts
@@ -1026,4 +1026,42 @@ export const offersProfileRouter = createRouter()
         message: 'Invalid token.',
       });
     },
+  })
+  .mutation('addToUserProfile', {
+    input: z.object({
+      profileId: z.string(),
+      token: z.string(),
+      userId: z.string(),
+    }),
+    async resolve({ ctx, input }) {
+      const profile = await ctx.prisma.offersProfile.findFirst({
+          where: {
+            id: input.profileId,
+          },
+      });
+
+      const profileEditToken = profile?.editToken;
+
+      // To validate user editing, OP or correct user
+      // TODO: improve validation process
+      if (profileEditToken === input.token) {
+        return await ctx.prisma.offersProfile.update({
+          data: {
+            user: {
+              connect: {
+                id: input.userId
+              }
+            }
+          },
+          where: {
+            id: input.profileId
+          }
+        })
+      }
+
+      throw new trpc.TRPCError({
+        code: 'UNAUTHORIZED',
+        message: 'Invalid token.',
+      });
+     }
   });