(()=>{var e={};e.id=6100,e.ids=[6100],e.modules={28303:e=>{function t(e){var t=Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}t.keys=()=>[],t.resolve=t,t.id=28303,e.exports=t},10846:e=>{"use strict";e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},44870:e=>{"use strict";e.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},29294:e=>{"use strict";e.exports=require("next/dist/server/app-render/work-async-storage.external.js")},63033:e=>{"use strict";e.exports=require("next/dist/server/app-render/work-unit-async-storage.external.js")},79428:e=>{"use strict";e.exports=require("buffer")},55511:e=>{"use strict";e.exports=require("crypto")},94735:e=>{"use strict";e.exports=require("events")},91645:e=>{"use strict";e.exports=require("net")},19771:e=>{"use strict";e.exports=require("process")},27910:e=>{"use strict";e.exports=require("stream")},41204:e=>{"use strict";e.exports=require("string_decoder")},66136:e=>{"use strict";e.exports=require("timers")},34631:e=>{"use strict";e.exports=require("tls")},79551:e=>{"use strict";e.exports=require("url")},28354:e=>{"use strict";e.exports=require("util")},74075:e=>{"use strict";e.exports=require("zlib")},4573:e=>{"use strict";e.exports=require("node:buffer")},77598:e=>{"use strict";e.exports=require("node:crypto")},53053:e=>{"use strict";e.exports=require("node:diagnostics_channel")},40495:(e,t,r)=>{"use strict";r.r(t),r.d(t,{patchFetch:()=>E,routeModule:()=>_,serverHooks:()=>h,workAsyncStorage:()=>N,workUnitAsyncStorage:()=>x});var i={};r.r(i),r.d(i,{GET:()=>S,PATCH:()=>g});var s=r(42706),n=r(28203),o=r(45994),a=r(65658),u=r(39187),l=r(98095),p=r(53721),m=r(71747),c=r(23951);let f=a.Ik({firstName:a.Yj().min(1),lastName:a.Yj().min(1),phone:a.Yj().optional(),role:a.Yj().min(1),status:a.k5(["active","inactive","pending_invitation"]),institutionIds:a.YO(a.Yj().min(1)).min(1)});async function d(e,t){let r=(0,c.T)(),i=`
    SELECT
      id,
      email,
      status,
      first_name,
      last_name,
      display_name,
      phone,
      role_id,
      institution_ids,
      profiles
    FROM users
    WHERE id = ?
      AND org_id = ?
    LIMIT 1
  `,[s]=await r.query(i,[e,t]);if(!s.length)return null;let n=s[0],o=String(n.first_name||"").trim(),a=String(n.last_name||"").trim(),u=String(n.display_name||"").trim(),l=function(e){let t=String(e||"").trim();if(!t)return{firstName:"",lastName:""};let r=t.split(/\s+/);return 1===r.length?{firstName:r[0],lastName:""}:{firstName:r[0],lastName:r.slice(1).join(" ")}}(u);return{id:String(n.id||"").trim(),firstName:o||l.firstName||"",lastName:a||l.lastName||"",displayName:u||String(`${o||l.firstName} ${a||l.lastName}`).trim(),email:String(n.email||"").trim().toLowerCase(),phone:String(n.phone||"").trim(),photoUrl:function(e){if(null==e)return"";if("object"==typeof e)return String(e.photoUrl||e.photoURL||"").trim();let t=String(e||"").trim();if(!t)return"";try{let e=JSON.parse(t);return String(e.photoUrl||e.photoURL||"").trim()}catch{return""}}(n.profiles),role:String(n.role_id||"").trim(),status:function(e){let t=String(e||"").trim().toLowerCase();return"inactive"===t?"inactive":"pending_invitation"===t?"pending_invitation":"active"}(n.status),institutionIds:function(e){if(Array.isArray(e))return e.map(e=>String(e||"").trim()).filter(e=>!!e);let t=String(e??"").trim();if(!t)return[];if(t.startsWith("[")&&t.endsWith("]"))try{let e=JSON.parse(t);if(Array.isArray(e))return e.map(e=>String(e||"").trim()).filter(e=>!!e)}catch{}return t.split(",").map(e=>e.trim()).filter(e=>!!e)}(n.institution_ids)}}async function S(e,{params:t}){try{if("mysql"!==(0,l.f)())return u.NextResponse.json({error:"Users API local deshabilitada."},{status:404});let r=(0,p.Z)(e);if(!r)return u.NextResponse.json({error:"No autenticado."},{status:401});if(!(0,m.s)(r,"users:get"))return u.NextResponse.json({error:"Sin permisos para ver usuario."},{status:403});let i=String(r.orgId||"").trim();if(!i)return u.NextResponse.json({error:"Sesion sin orgId."},{status:403});let s=String((await t).id||"").trim();if(!s)return u.NextResponse.json({error:"ID invalido."},{status:400});let n=await d(s,i);if(!n)return u.NextResponse.json({error:"Usuario no encontrado."},{status:404});let o=(0,c.T)(),[a]=await o.query(`
        SELECT id, name
        FROM roles
        ORDER BY name ASC
      `),f=a.map(e=>({id:String(e.id||"").trim(),name:String(e.name||e.id||"").trim()})),[S]=await o.query(`
        SELECT id, name
        FROM institutions
        WHERE org_id = ?
        ORDER BY name ASC
      `,[i]),g=S.map(e=>({id:String(e.id||"").trim(),name:String(e.name||e.id||"").trim()}));return u.NextResponse.json({user:n,roles:f,institutions:g})}catch(e){return console.error("[GET /api/users/[id]] error:",e),u.NextResponse.json({error:"Error interno."},{status:500})}}async function g(e,{params:t}){try{if("mysql"!==(0,l.f)())return u.NextResponse.json({error:"Users API local deshabilitada."},{status:404});let r=(0,p.Z)(e);if(!r)return u.NextResponse.json({error:"No autenticado."},{status:401});if(!(0,m.s)(r,"users:update"))return u.NextResponse.json({error:"Sin permisos para actualizar usuario."},{status:403});let i=String(r.orgId||"").trim();if(!i)return u.NextResponse.json({error:"Sesion sin orgId."},{status:403});let s=String((await t).id||"").trim();if(!s)return u.NextResponse.json({error:"ID invalido."},{status:400});let n=await e.json().catch(()=>null),o=f.safeParse(n);if(!o.success)return u.NextResponse.json({error:"Payload invalido."},{status:400});let a=await d(s,i);if(!a)return u.NextResponse.json({error:"Usuario no encontrado."},{status:404});let S=o.data,g=String(S.role||"").trim();if(g!==a.role&&!(0,m.s)(r,"users:manage_roles"))return u.NextResponse.json({error:"Sin permisos para modificar rol de usuario."},{status:403});let _=String(S.firstName||"").trim(),N=String(S.lastName||"").trim(),x=String(`${_} ${N}`).trim(),h=String(S.phone||"").trim(),E=String(S.status||"").trim(),T=S.institutionIds.map(e=>String(e||"").trim()).filter(e=>!!e),R=(0,c.T)(),A=`
      UPDATE users
      SET
        first_name = ?,
        last_name = ?,
        display_name = ?,
        phone = ?,
        role_id = ?,
        status = ?,
        institution_ids = ?,
        updated_at = UTC_TIMESTAMP()
      WHERE id = ?
        AND org_id = ?
      LIMIT 1
    `;return await R.query(A,[_,N,x,h||null,g,E,JSON.stringify(T),s,i]),u.NextResponse.json({success:!0})}catch(e){return console.error("[PATCH /api/users/[id]] error:",e),u.NextResponse.json({error:"Error interno."},{status:500})}}let _=new s.AppRouteRouteModule({definition:{kind:n.RouteKind.APP_ROUTE,page:"/api/users/[id]/route",pathname:"/api/users/[id]",filename:"route",bundlePath:"app/api/users/[id]/route"},resolvedPagePath:"C:\\omrwebapp-git-roregar.cl\\src\\app\\api\\users\\[id]\\route.ts",nextConfigOutput:"standalone",userland:i}),{workAsyncStorage:N,workUnitAsyncStorage:x,serverHooks:h}=_;function E(){return(0,o.patchFetch)({workAsyncStorage:N,workUnitAsyncStorage:x})}},96487:()=>{},78335:()=>{},71747:(e,t,r)=>{"use strict";function i(e){return String(e||"").trim().toLowerCase()}function s(e,t){if(!e)return!1;if(function(e){let t=i(e);return"admin"===t||t.startsWith("admin_")||t.includes(":admin")}(e.roleId))return!0;let r=i(t);return(e.permissions||[]).some(e=>i(e)===r)}r.d(t,{s:()=>s})},98095:(e,t,r)=>{"use strict";function i(){return"mysql"===String(process.env.AUTH_MODE||process.env.NEXT_PUBLIC_AUTH_MODE||"").trim().toLowerCase()?"mysql":"firebase"}r.d(t,{f:()=>i})},23951:(e,t,r)=>{"use strict";r.d(t,{T:()=>u});var i=r(60820);let s=null;function n(e){for(let t of e){let e=process.env[t];if(e&&String(e).trim())return String(e).trim()}}function o(e,t){let r=n(e);if(!r)throw Error(`Missing ${t}. Set one of: ${e.join(", ")}`);return r}function a(e,t){if(!e)return t;let r=Number(e);return Number.isFinite(r)?r:t}function u(){if(s)return s;let e=o(["AUTH_DB_HOST","DB_HOST"],"database host"),t=o(["AUTH_DB_USER","DB_USERNAME","DB_USER"],"database user"),r=o(["AUTH_DB_PASSWORD","DB_PASSWORD"],"database password"),u=o(["AUTH_DB_NAME","DB_DATABASE"],"database name"),l=a(n(["AUTH_DB_PORT","DB_PORT"]),3306),p=a(n(["AUTH_DB_POOL_SIZE","DB_POOL_SIZE"]),10);return s=i.createPool({host:e,port:l,user:t,password:r,database:u,waitForConnections:!0,connectionLimit:p,queueLimit:0,charset:"utf8mb4"})}},53721:(e,t,r)=>{"use strict";r.d(t,{Z:()=>s});var i=r(89249);function s(e){let t=String(e.cookies.get(i.CA())?.value||"").trim();if(!t)return null;let r=(0,i.zP)(t);return r?.user||null}},89249:(e,t,r)=>{"use strict";r.d(t,{$G:()=>d,C0:()=>S,CA:()=>l,Q7:()=>m,zP:()=>f});var i=r(77598),s=r.n(i);let n="omr_local_session";function o(e){return(Buffer.isBuffer(e)?e:Buffer.from(e)).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function a(e){let t=String(e||"").replace(/-/g,"+").replace(/_/g,"/"),r=t.length%4==0?"":"=".repeat(4-t.length%4);return Buffer.from(t+r,"base64")}function u(){return String(process.env.AUTH_SESSION_SECRET||process.env.NEXTAUTH_SECRET||process.env.AUTH_DB_PASSWORD||"").trim()||"omr-local-session-dev-secret-change-me"}function l(){return String(process.env.AUTH_SESSION_COOKIE_NAME||n).trim()||n}function p(){let e=Number(process.env.AUTH_SESSION_TTL_HOURS||168);return Math.round(3600*(Number.isFinite(e)&&e>0?e:168))}function m(e){let t=Math.floor(Date.now()/1e3),r={v:1,iat:t,exp:t+p(),user:e},i=o(JSON.stringify({alg:"HS256",typ:"JWT"})),n=o(JSON.stringify(r)),a=`${i}.${n}`,l=o(s().createHmac("sha256",u()).update(a).digest());return`${a}.${l}`}function c(e){try{return JSON.parse(e)}catch{return null}}function f(e){let t=String(e||"").trim().split(".");if(3!==t.length)return null;let[r,i,n]=t;if(!r||!i||!n)return null;let l=`${r}.${i}`,p=o(s().createHmac("sha256",u()).update(l).digest()),m=Buffer.from(p),f=Buffer.from(n);if(m.length!==f.length||!s().timingSafeEqual(m,f))return null;let d=c(a(r).toString("utf8"));if(!d||"HS256"!==d.alg||"JWT"!==d.typ)return null;let S=c(a(i).toString("utf8"));if(!S||1!==S.v)return null;let g=Math.floor(Date.now()/1e3);if(!Number.isFinite(S.exp)||S.exp<=g)return null;let _=S.user;return _&&String(_.id||"").trim()&&String(_.email||"").trim()?S:null}function d(e,t){e.cookies.set(l(),t,{httpOnly:!0,sameSite:"lax",secure:!0,path:"/",maxAge:p()})}function S(e){e.cookies.set(l(),"",{httpOnly:!0,sameSite:"lax",secure:!0,path:"/",maxAge:0})}}};var t=require("../../../../webpack-runtime.js");t.C(e);var r=e=>t(t.s=e),i=t.X(0,[1989,5452,820,5658],()=>r(40495));module.exports=i})();