"use strict";async function verifyGoogleToken(e){return(await client.verifyIdToken({idToken:e,audience:process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID})).getPayload()}async function fetchGoogleUserInfo(e){const r=await fetch(`https://www.googleapis.com/oauth2/v3/userinfo?access_token=${e}`);if(!r.ok)throw(0,error_1.createError)({statusCode:401,message:"Failed to fetch user info from Google"});return r.json()}function sanitizeName(e){return e.replace(/[^\p{L}\s]/gu,"")}function isValidName(e){return/^[\p{L}\s]+$/u.test(e)}Object.defineProperty(exports,"__esModule",{value:!0});exports.metadata=void 0;const google_auth_library_1=require("google-auth-library"),db_1=require("@b/db"),affiliate_1=require("@b/utils/affiliate"),utils_1=require("../utils"),query_1=require("@b/utils/query"),error_1=require("@b/utils/error"),console_1=require("@b/utils/console"),client=new google_auth_library_1.OAuth2Client(process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID);exports.metadata={summary:"Registers a new user with Google",operationId:"registerUserWithGoogle",tags:["Auth"],description:"Registers a new user using Google and returns a session token",requiresAuth:!1,logModule:"REGISTER",logTitle:"Google registration",requestBody:{required:!0,content:{"application/json":{schema:utils_1.userRegisterSchema}}},responses:{200:{description:"User registered successfully",content:{"application/json":{schema:{type:"object",properties:utils_1.userRegisterResponseSchema}}}},500:query_1.serverErrorResponse}};exports.default=async e=>{const{body:r,ctx:s}=e,{token:o,ref:t}=r;try{null==s||s.step("Validating Google token");if(!o){null==s||s.fail("Google token is required");throw(0,error_1.createError)({statusCode:400,message:"Google token is required"})}null==s||s.step("Verifying Google token");let e;try{e=await verifyGoogleToken(o)}catch(r){null==s||s.step("Trying alternative token verification");e=await fetchGoogleUserInfo(o)}if(!e){null==s||s.fail("Invalid Google token");throw(0,error_1.createError)({statusCode:400,message:"Invalid Google token"})}const{sub:r,email:i,given_name:a,family_name:n}=e;null==s||s.step("Validating Google user data");if(!(r&&i&&a&&n)){null==s||s.fail("Incomplete user information from Google");throw(0,error_1.createError)({statusCode:400,message:"Incomplete user information from Google"})}null==s||s.step("Sanitizing user names");const l=sanitizeName(a),u=sanitizeName(n);if(!isValidName(l)||!isValidName(u)){null==s||s.fail("Invalid name format");throw(0,error_1.createError)({statusCode:400,message:"First name and last name must only contain letters and spaces"})}null==s||s.step(`Checking if user ${i} exists`);let d=await db_1.models.user.findOne({where:{email:i}}),c=!1;if(d){null==s||s.step("User exists, checking provider link");if(!await db_1.models.providerUser.findOne({where:{providerUserId:r,provider:"GOOGLE"}})){null==s||s.step("Creating Google provider link for existing user");await db_1.models.providerUser.create({provider:"GOOGLE",providerUserId:r,userId:d.id})}}else{null==s||s.step("Creating new user account");const e="true"===process.env.NEXT_PUBLIC_DEMO_STATUS?"Admin":"User";await db_1.models.role.upsert({name:e});const o=await db_1.models.role.findOne({where:{name:e}});if(!o)throw(0,error_1.createError)({statusCode:500,message:"Role not found after upsert."});d=await db_1.models.user.create({firstName:l,lastName:u,email:i,roleId:o.id,emailVerified:!0,settings:{email:!0,sms:!1,push:!1}});null==s||s.step("Creating Google provider link");await db_1.models.providerUser.create({provider:"GOOGLE",providerUserId:r,userId:d.id});if(t){null==s||s.step(`Processing referral code: ${t}`);try{await(0,affiliate_1.handleReferralRegister)(t,d.id)}catch(e){null==s||s.step("Failed to process referral code","warn");console_1.logger.error("AUTH","Error handling referral registration",e)}}c=!0}null==s||s.step("Generating session tokens");const g=await(0,utils_1.returnUserWithTokens)({user:d,message:c?"You have been registered successfully":"You have been logged in successfully"});null==s||s.success(c?`User ${i} registered with Google`:`User ${i} logged in with Google`);return g}catch(e){null==s||s.fail(e.message||"Google registration/login failed");throw e}};