"use strict";(()=>{var e={};e.id=1061,e.ids=[1061],e.modules={10846:e=>{e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},44870:e=>{e.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},29294:e=>{e.exports=require("next/dist/server/app-render/work-async-storage.external.js")},63033:e=>{e.exports=require("next/dist/server/app-render/work-unit-async-storage.external.js")},79428:e=>{e.exports=require("buffer")},79646:e=>{e.exports=require("child_process")},55511:e=>{e.exports=require("crypto")},14985:e=>{e.exports=require("dns")},94735:e=>{e.exports=require("events")},29021:e=>{e.exports=require("fs")},81630:e=>{e.exports=require("http")},55591:e=>{e.exports=require("https")},91645:e=>{e.exports=require("net")},21820:e=>{e.exports=require("os")},33873:e=>{e.exports=require("path")},19771:e=>{e.exports=require("process")},27910:e=>{e.exports=require("stream")},41204:e=>{e.exports=require("string_decoder")},66136:e=>{e.exports=require("timers")},34631:e=>{e.exports=require("tls")},79551:e=>{e.exports=require("url")},28354:e=>{e.exports=require("util")},74075:e=>{e.exports=require("zlib")},4573:e=>{e.exports=require("node:buffer")},77598:e=>{e.exports=require("node:crypto")},53053:e=>{e.exports=require("node:diagnostics_channel")},50229:(e,r,t)=>{t.r(r),t.d(r,{patchFetch:()=>j,routeModule:()=>R,serverHooks:()=>_,workAsyncStorage:()=>I,workUnitAsyncStorage:()=>S});var a={};t.r(a),t.d(a,{POST:()=>f});var n=t(42706),o=t(28203),s=t(45994),i=t(77598),u=t.n(i),p=t(34926),d=t(65658),c=t(39187),l=t(98095),m=t(8089),g=t(70357),x=t(42770),h=t(50675);let E=d.Ik({firstName:d.Yj().min(1),lastName:d.Yj().min(1),email:d.Yj().email(),phone:d.Yj().optional(),role:d.Yj().min(1),institutionIds:d.YO(d.Yj().min(1)).min(1),continueUrl:d.Yj().url().optional()});async function f(e){try{var r;if("mysql"!==(0,l.f)())return c.NextResponse.json({error:"Auth local deshabilitada."},{status:404});let t=function(e){let r=String(e.headers.get("authorization")||"").trim().match(/^Bearer\s+(.+)$/i);return String(r?.[1]||"").trim()}(e);if(!t)return c.NextResponse.json({error:"Unauthorized"},{status:401});let{auth:a,db:n}=(0,m.j)(),o=await a.verifyIdToken(t),s=String(o.uid||"").trim();if(!s)return c.NextResponse.json({error:"Unauthorized"},{status:401});let i=await n.doc(`users/${s}`).get();if(!i.exists)return c.NextResponse.json({error:"Caller user not found."},{status:403});let d=i.data()||{},f=String(d.role||""),R=String(d.orgId||"");if(!R)return c.NextResponse.json({error:"Caller has no orgId."},{status:403});if(!["admin","admin_fundacion","administrador_colegio"].includes(f))return c.NextResponse.json({error:"Permission denied."},{status:403});let I=await e.json().catch(()=>null),S=E.safeParse(I);if(!S.success)return c.NextResponse.json({error:"Payload invalido."},{status:400});let _=S.data.firstName.trim(),j=S.data.lastName.trim(),q=(r=S.data.email,String(r||"").trim().toLowerCase()),w=String(S.data.phone||"").trim(),A=S.data.role.trim(),C=S.data.institutionIds.map(e=>e.trim()),O=function(e,r){let t=new URL(String(r||"").trim()||String(e.headers.get("origin")||"").trim()||e.nextUrl.origin);if(!("localhost"===t.hostname||"127.0.0.1"===t.hostname||"0.0.0.0"===t.hostname)&&"https:"!==t.protocol)throw Error("continueUrl/origin invalido: fuera de localhost debe ser https.");return t.origin}(e,S.data.continueUrl),T=`${_} ${j}`.trim(),v=C.map(e=>n.doc(`institutions/${e}`));for(let e of v.length?await n.getAll(...v):[]){if(!e.exists)return c.NextResponse.json({error:"Institution no existe."},{status:400});let r=e.data()||{};if(String(r.orgId||"")!==R)return c.NextResponse.json({error:"Institution fuera de tu org."},{status:403})}if(await (0,h.t7)(q)||!(await n.collection("users").where("email","==",q).limit(1).get()).empty)return c.NextResponse.json({error:"Ya existe un usuario con ese email."},{status:409});let B="";try{B=(await a.getUserByEmail(q)).uid}catch{B=(await a.createUser({email:q,emailVerified:!1,displayName:T,disabled:!1})).uid}await n.doc(`users/${B}`).set({id:B,uid:B,firstName:_,lastName:j,displayName:T,email:q,phone:w,orgId:R,institutionIds:C,role:A,status:"pending",createdAt:new Date,updatedAt:new Date,createdByUid:s,updatedByUid:s},{merge:!0});let U=u().randomBytes(32).toString("hex"),N=await p.Ay.hash(U,12);await (0,h.Z2)({email:q,passwordHash:N,status:"pending",firebaseUid:B,firstName:_,lastName:j,displayName:T,phone:w,role:A,orgId:R,institutionIds:C});let{token:P,expiresAt:y}=await (0,x.Vo)(q),b=`${O}/set-password?mode=reset&email=${encodeURIComponent(q)}&token=${encodeURIComponent(P)}`,$=[`Hola ${T},`,"","Tu cuenta en OMR SEG fue creada.","Para activar acceso y crear tu contrasena, abre este enlace:",b,"",`Este enlace expira el ${y.toISOString()}.`].join("\n"),k=`
      <p>Hola <strong>${T}</strong>,</p>
      <p>Tu cuenta en <strong>OMR SEG</strong> fue creada.</p>
      <p><a href="${b}">Activar cuenta y crear contrasena</a></p>
      <p>Si el boton no funciona, usa este enlace:</p>
      <p>${b}</p>
      <p>Este enlace expira el <strong>${y.toISOString()}</strong>.</p>
    `;return await (0,g.x)({to:q,subject:"OMR SEG - Activacion de cuenta",text:$,html:k}),c.NextResponse.json({success:!0,uid:B})}catch(e){if(console.error("[POST /api/auth/admin/create-user] error:",e),e?.code==="auth/id-token-expired"||e?.code==="auth/argument-error")return c.NextResponse.json({error:"Invalid auth token."},{status:401});return c.NextResponse.json({error:"Error interno."},{status:500})}}let R=new n.AppRouteRouteModule({definition:{kind:o.RouteKind.APP_ROUTE,page:"/api/auth/admin/create-user/route",pathname:"/api/auth/admin/create-user",filename:"route",bundlePath:"app/api/auth/admin/create-user/route"},resolvedPagePath:"C:\\omrwebapp-git-roregar.cl\\src\\app\\api\\auth\\admin\\create-user\\route.ts",nextConfigOutput:"standalone",userland:a}),{workAsyncStorage:I,workUnitAsyncStorage:S,serverHooks:_}=R;function j(){return(0,s.patchFetch)({workAsyncStorage:I,workUnitAsyncStorage:S})}},8089:(e,r,t)=>{t.d(r,{j:()=>o});let a=require("firebase-admin");function n(e){return(process.env[e]||"").trim()}function o(){if(a.apps.length){let e=a.app();return{db:a.firestore(e),auth:a.auth(e),storage:a.storage(e),app:e}}let e=function(){let e=process.env.FIREBASE_CONFIG||"";if(!e)return{};try{return JSON.parse(e)||{}}catch{return{}}}(),r=n("FIREBASE_PROJECT_ID")||n("NEXT_PUBLIC_FIREBASE_PROJECT_ID")||n("GOOGLE_CLOUD_PROJECT")||n("GCLOUD_PROJECT")||String(e.projectId||"").trim(),t=n("FIREBASE_STORAGE_BUCKET")||n("NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET")||String(e.storageBucket||"").trim(),o=n("FIREBASE_CLIENT_EMAIL"),s=(process.env.FIREBASE_PRIVATE_KEY||"").replace(/\\n/g,"\n").replace(/^"|"$/g,"");if(!r)throw Error("Missing projectId env (FIREBASE_PROJECT_ID or NEXT_PUBLIC_FIREBASE_PROJECT_ID)");if(!t)throw Error("Missing storage bucket env (FIREBASE_STORAGE_BUCKET or NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET)");let i=!!(o&&s),u=a.initializeApp({credential:i?a.credential.cert({projectId:r,clientEmail:o,privateKey:s}):a.credential.applicationDefault(),projectId:r,storageBucket:t});return{db:a.firestore(u),auth:a.auth(u),storage:a.storage(u),app:u}}}};var r=require("../../../../../webpack-runtime.js");r.C(e);var t=e=>r(r.s=e),a=r.X(0,[1989,5452,6907,4926,8721,4032],()=>t(50229));module.exports=a})();