(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,31299,e=>{"use strict";var r=e.i(43476),o=e.i(71645),a=e.i(18566),s=e.i(86964),t=e.i(46696);let n=(0,o.createContext)(null),l=["/","/login","/register","/forgot-password","/reset-password"],i=["admin","gestor","contablista","operador"],u={admin:"/dashboard",gestor:"/dashboard/Produtos_servicos/Stock",contablista:"/dashboard/relatorios",operador:"/dashboard/Vendas/Nova_venda"};e.s(["AuthContext",0,n,"AuthProvider",0,function({children:e}){let d=(0,a.useRouter)(),c=(0,a.usePathname)(),[h,m]=(0,o.useState)(null),[g,p]=(0,o.useState)(!0),v=(0,o.useRef)(!1),A=!!c&&l.includes(c),f=(0,o.useCallback)(async()=>{if(console.log("[AuthProvider] fetchUser iniciado"),A)return void p(!1);try{let e=await s.authApi.me();if(e.data?.success&&e.data.user){let r={...e.data.user,empresa:e.data.empresa};if(!i.includes(r.role)){console.warn("[AuthProvider] Role não reconhecida:",r.role),m(null),(0,s.clearTenant)(),A||"/login"===c||(d.replace("/login"),t.toast.error(`Role "${r.role}" n\xe3o autorizada. Contacte o administrador.`));return}m(r),e.data.empresa?.id&&(0,s.setTenant)({id:e.data.empresa.id,subdomain:e.data.empresa.subdomain}),console.log("[AuthProvider] User atualizado com sucesso:",{id:r.id,role:r.role,empresa:r.empresa?.nome})}else m(null)}catch(e){console.error("[AuthProvider] fetchUser falhou:",e),m(null)}finally{p(!1)}},[A,c,d]);(0,o.useEffect)(()=>{v.current||(v.current=!0,A?p(!1):f())},[f,A]);let P=(0,o.useCallback)(async(e,r)=>{p(!0);try{await s.authApi.getCsrf();let o=(await s.authApi.login(e,r)).data;if(!o.success)throw Error(o.message||"Erro no login");if(!o.user)throw Error("Dados do usuário não retornados");if(!i.includes(o.user.role))return console.warn("[AuthProvider] Login com role inválida:",o.user.role),t.toast.error(`Role "${o.user.role}" n\xe3o autorizada. Contacte o administrador.`),{success:!1,message:"Role não autorizada"};o.empresa?((0,s.setTenant)(o.empresa),console.log("[AuthProvider] Tenant guardado no login:",o.empresa.id)):console.warn("[AuthProvider] Login sem empresa!");let a={...o.user,empresa:o.empresa};m(a),console.log("[AuthProvider] Login bem-sucedido:",{id:a.id,role:a.role,name:a.name}),t.toast.success(`Bem-vindo, ${o.user.name}!`),await new Promise(e=>setTimeout(e,100));let n=u[a.role]||"/dashboard";return console.log("[AuthProvider] Redirecionando para:",{role:a.role,destination:n}),d.replace(n),{success:!0}}catch(r){let e=r.response?.data?.message||r.message||"Erro ao fazer login";return t.toast.error(e),{success:!1,message:e}}finally{p(!1)}},[d]),b=(0,o.useCallback)(async()=>{p(!0);let e=!1,r="";try{await s.authApi.logout(),e=!0,r="Logout no servidor realizado",console.log("[AuthProvider]",r)}catch(e){console.warn("[AuthProvider]",r="Erro no logout do servidor",e)}return m(null),(0,s.clearTenant)(),t.toast.success("Logout realizado"),v.current=!1,d.replace("/login"),{success:!0,message:e?"Logout realizado com sucesso":"Logout local realizado"}},[d]),w=(0,o.useCallback)(async()=>{console.log("[AuthProvider] refreshUser chamado - Forçando atualização"),v.current=!1,m(null),p(!0);try{await f()}catch(e){console.error("[AuthProvider] Erro no refreshUser",e)}},[f]);return(0,r.jsx)(n.Provider,{value:{user:h,loading:g,isAuthenticated:!!h,login:P,logout:b,refreshUser:w},children:e})},"useAuth",0,function(){let e=(0,o.useContext)(n);if(!e)throw Error("useAuth deve ser usado dentro de AuthProvider");return e}])}]);