import{GenericError as e}from"../utils/errors/ErrorsClass.mjs";import{ProjectModel as t}from"../models/project.model.mjs";import{getProjectById as n}from"./project.service.mjs";import{randomBytes as r}from"node:crypto";const i=()=>({clientId:r(16).toString(`hex`),clientSecret:r(32).toString(`hex`)}),a=async(r,a,o)=>{let{clientId:s,clientSecret:c}=i(),l={...r,clientId:s,clientSecret:c,userId:o.id,accessToken:[],grants:r.grants};if((await t.updateOne({_id:a},{$push:{oAuth2Access:l}})).modifiedCount===0)throw new e(`ACCESS_KEY_CREATION_FAILED`,{accessKeyData:r,projectId:a,userId:o.id});let u=(await n(a)).oAuth2Access.find(e=>e.clientId===s);if(!u)throw new e(`ACCESS_KEY_CREATION_FAILED`,{accessKeyData:r,projectId:a,userId:o.id});return u},o=async(n,r,i)=>{let a=r.oAuth2Access.find(e=>e.clientId===n&&String(e.userId)===String(i));if(!a)throw new e(`ACCESS_KEY_NOT_FOUND`,{clientId:n,projectId:r.id});if((await t.updateOne({"oAuth2Access.clientId":n,"oAuth2Access.userId":String(i)},{$pull:{oAuth2Access:{clientId:n}}})).modifiedCount===0)throw new e(`ACCESS_KEY_DELETION_FAILED`,{clientId:n,projectId:r.id});return a},s=async(r,a,o)=>{let s=await t.findOne({_id:a,"oAuth2Access.clientId":r,"oAuth2Access.userId":String(o)});if(!s)throw new e(`PROJECT_NOT_FOUND`,{clientId:r,projectId:a,userId:o});let c=s.oAuth2Access.find(e=>e.clientId===r);if(!c)throw new e(`ACCESS_KEY_NOT_FOUND`,{clientId:r,projectId:s.id});let{clientSecret:l}=i();if((await t.updateOne({"oAuth2Access.clientId":r,"oAuth2Access.userId":String(o)},{$set:{"oAuth2Access.$.clientId":c.clientId,"oAuth2Access.$.clientSecret":l}})).modifiedCount===0)throw new e(`ACCESS_KEY_UPDATE_FAILED`,{clientId:r,projectId:a});let u=await n(a),d=u.oAuth2Access.find(e=>e.clientId===c.clientId);if(!d)throw new e(`ACCESS_KEY_CREATION_FAILED`,{accessKeyData:u.oAuth2Access,projectId:a,userId:o});return d};export{a as addNewAccessKey,o as deleteAccessKey,s as refreshAccessKey};
//# sourceMappingURL=projectAccessKey.service.mjs.map