"use strict";(()=>{var e={};e.id=2654,e.ids=[2654],e.modules={53524:e=>{e.exports=require("@prisma/client")},98432:e=>{e.exports=require("bcryptjs")},72934:e=>{e.exports=require("next/dist/client/components/action-async-storage.external.js")},54580:e=>{e.exports=require("next/dist/client/components/request-async-storage.external.js")},45869:e=>{e.exports=require("next/dist/client/components/static-generation-async-storage.external.js")},20399:e=>{e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},30517:e=>{e.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},27790:e=>{e.exports=require("assert")},78893:e=>{e.exports=require("buffer")},84770:e=>{e.exports=require("crypto")},17702:e=>{e.exports=require("events")},32615:e=>{e.exports=require("http")},35240:e=>{e.exports=require("https")},86624:e=>{e.exports=require("querystring")},17360:e=>{e.exports=require("url")},21764:e=>{e.exports=require("util")},71568:e=>{e.exports=require("zlib")},68545:(e,a,n)=>{n.r(a),n.d(a,{originalPathname:()=>g,patchFetch:()=>A,requestAsyncStorage:()=>y,routeModule:()=>h,serverHooks:()=>f,staticGenerationAsyncStorage:()=>w});var t={};n.r(t),n.d(t,{POST:()=>d});var o=n(73278),s=n(45002),r=n(54877),i=n(71309),l=n(18445),c=n(73275),u=n(82208),p=n(37642);let m=p.Ry({amount:p.Rx().positive("Amount must be positive").min(500,"Minimum amount is UGX 500"),phoneNumber:p.Z_().regex(/^\+256[0-9]{9}$/,"Phone number must be in international format (+256XXXXXXXXX)"),currency:p.Z_().default("UGX"),description:p.Z_().optional()});async function d(e){try{let a,n;let t=await (0,l.getServerSession)(c.Lz);if(!t?.user?.id)return i.NextResponse.json({error:"Unauthorized"},{status:401});let o=t.user.id,s=t.user.isTenant?"tenant":t.user.isTechnician?"technician":"user",r=await e.json(),p=m.safeParse(r);if(!p.success)return i.NextResponse.json({error:"Validation failed",details:p.error.issues},{status:400});let{amount:d,phoneNumber:h,currency:y,description:w}=p.data;if("tenant"===s){let e=await u._.tenant.findUnique({where:{id:o},select:{companyId:!0}});if(!e?.companyId)return i.NextResponse.json({error:"Tenant not associated with a company"},{status:400});n=e.companyId,a=await u._.$queryRaw`
        SELECT w.*, c.code as currency_code, c.symbol as currency_symbol, c.name as currency_name
        FROM wallets w
        LEFT JOIN currencies c ON w.currencyId = c.id
        WHERE w.userType = 'tenant' AND w.tenantId = ${o}
        LIMIT 1
      `}else if("technician"===s){let e=await u._.technician.findUnique({where:{id:o},select:{companyId:!0}});if(!e?.companyId)return i.NextResponse.json({error:"Technician not associated with a company"},{status:400});n=e.companyId,a=await u._.$queryRaw`
        SELECT w.*, c.code as currency_code, c.symbol as currency_symbol, c.name as currency_name
        FROM wallets w
        LEFT JOIN currencies c ON w.currencyId = c.id
        WHERE w.userType = 'technician' AND w.technicianId = ${o}
        LIMIT 1
      `}else{let e=await u._.user.findUnique({where:{id:o},select:{companyId:!0,role:!0}});if(!e?.companyId)return i.NextResponse.json({error:"User not associated with a company"},{status:400});n=e.companyId,a=await u._.$queryRaw`
        SELECT w.*, c.code as currency_code, c.symbol as currency_symbol, c.name as currency_name
        FROM wallets w
        LEFT JOIN currencies c ON w.currencyId = c.id
        WHERE w.userType = 'user' AND w.userId = ${o}
        LIMIT 1
      `}if(0===a.length)return i.NextResponse.json({error:"Wallet not found"},{status:404});let f={id:a[0].id,balance:a[0].balance,companyId:a[0].companyId,currency:{code:a[0].currency_code,symbol:a[0].currency_symbol,name:a[0].currency_name},status:a[0].status},g=`MM_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,A=crypto.randomUUID();await u._.$executeRaw`
      INSERT INTO wallet_transactions (id, walletId, companyId, transactionType, amount, currency, description, paymentMethod, status, metadata, createdAt, updatedAt)
      VALUES (${A}, ${f.id}, ${n}, 'top_up', ${d}, ${y}, ${w||`Mobile Money top-up via ${h}`}, 'mobile_money', 'pending', ${JSON.stringify({phoneNumber:h,reference:g,relworxReference:null})}, NOW(), NOW())
    `,console.log("Calling Relworx API with:",{account_no:process.env.REL_BUSINESS_ACCOUNT_NO,reference:g,msisdn:h,currency:y,amount:d,description:w||`Wallet top-up for ${t.user.email}`});let N=await fetch("https://payments.relworx.com/api/mobile-money/request-payment",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/vnd.relworx.v2",Authorization:`Bearer ${process.env.REL_APIKEY}`},body:JSON.stringify({account_no:process.env.REL_BUSINESS_ACCOUNT_NO,reference:g,msisdn:h,currency:y,amount:d,description:w||`Wallet top-up for ${t.user.email}`})});console.log("Relworx response status:",N.status),console.log("Relworx response headers:",Object.fromEntries(N.headers.entries()));let x=await N.text();if(console.log("Relworx response body:",x),!N.ok){let e;await u._.$executeRaw`
        UPDATE wallet_transactions SET status = 'failed', updatedAt = NOW() WHERE id = ${A}
      `;try{e=await N.json()}catch(a){e={message:x||"Unknown error from Relworx API"}}return console.error("Relworx API error:",e),i.NextResponse.json({error:"Failed to initiate mobile money payment",details:e},{status:400})}let T=await N.json();return await u._.$executeRaw`
      UPDATE wallet_transactions
      SET metadata = ${JSON.stringify({phoneNumber:h,reference:g,relworxReference:T.internal_reference})}
      WHERE id = ${A}
    `,i.NextResponse.json({transaction:{id:A,reference:g,relworxReference:T.internal_reference,amount:d,currency:y,phoneNumber:h,status:"pending"},message:"Mobile money payment request sent successfully. Please check your phone and complete the payment."})}catch(e){return console.error("Error processing mobile money payment:",e),i.NextResponse.json({error:"Internal server error"},{status:500})}}let h=new o.AppRouteRouteModule({definition:{kind:s.x.APP_ROUTE,page:"/api/wallet/mobile-money/route",pathname:"/api/wallet/mobile-money",filename:"route",bundlePath:"app/api/wallet/mobile-money/route"},resolvedPagePath:"c:\\xampp\\htdocs\\propmaster.io\\src\\app\\api\\wallet\\mobile-money\\route.ts",nextConfigOutput:"standalone",userland:t}),{requestAsyncStorage:y,staticGenerationAsyncStorage:w,serverHooks:f}=h,g="/api/wallet/mobile-money/route";function A(){return(0,r.patchFetch)({serverHooks:f,staticGenerationAsyncStorage:w})}},73275:(e,a,n)=>{n.d(a,{Gv:()=>c,Lz:()=>i,c_:()=>l});var t=n(76214),o=n(98432),s=n.n(o),r=n(82208);let i={providers:[(0,t.Z)({name:"credentials",credentials:{email:{label:"Email",type:"email"},password:{label:"Password",type:"password"}},async authorize(e){if(console.log("Auth: Starting authentication for email:",e?.email),!e?.email||!e?.password)return console.log("Auth: Missing credentials"),null;try{console.log("Auth: Checking users table for:",e.email);let a=await r._.user.findUnique({where:{email:e.email},include:{company:{include:{subscriptionPlan:!0}}}});console.log("Auth: User lookup result:",a?`Found user with role: ${a.role}`:"No user found");let n=!1,t=!1;if(a&&"tenant"===a.role){console.log("Auth: User has tenant role, checking tenants table first");try{let t=await r._.tenant.findFirst({where:{email:e.email},include:{company:{include:{subscriptionPlan:!0}},unit:{include:{property:{include:{estate:!0}}}}}});if(console.log("Auth: Tenant lookup result:",t?"Found tenant":"No tenant found"),!t||!t.passwordHash)return console.log("Auth: No tenant found or no password hash, cannot authenticate"),null;{console.log("Auth: Tenant has password hash, verifying password");let o=await s().compare(e.password,t.passwordHash);if(console.log("Auth: Tenant password verification result:",o),!o)return console.log("Auth: Tenant password verification failed"),null;a={id:t.id,email:t.email,passwordHash:t.passwordHash,firstName:t.firstName,lastName:t.lastName,phone:t.phone,role:"tenant",companyId:t.companyId,company:t.company,avatarUrl:null,commissionRate:null,commissionDueDay:null,agreementDocument:null,emailVerified:!0,emailVerifiedAt:null,lastLoginAt:null,passwordResetToken:null,passwordResetExpires:null,preferences:{},timezone:"Africa/Kampala",createdAt:t.createdAt,updatedAt:t.updatedAt,deletedAt:null},n=!0,console.log("Auth: Tenant authentication successful")}}catch(e){return console.error("Auth: Error querying tenants table:",e),null}}else if(!a){console.log("Auth: User not found in users table, checking tenants table for:",e.email);try{let t=await r._.tenant.findFirst({where:{email:e.email},include:{company:{include:{subscriptionPlan:!0}},unit:{include:{property:{include:{estate:!0}}}}}});if(console.log("Auth: Tenant lookup result:",t?"Found tenant":"No tenant found"),t&&t.passwordHash){console.log("Auth: Tenant has password hash, verifying password");let o=await s().compare(e.password,t.passwordHash);console.log("Auth: Password verification result:",o),o?(a={id:t.id,email:t.email,passwordHash:t.passwordHash,firstName:t.firstName,lastName:t.lastName,phone:t.phone,role:"tenant",companyId:t.companyId,company:t.company,avatarUrl:null,commissionRate:null,commissionDueDay:null,agreementDocument:null,emailVerified:!0,emailVerifiedAt:null,lastLoginAt:null,passwordResetToken:null,passwordResetExpires:null,preferences:{},timezone:"Africa/Kampala",createdAt:t.createdAt,updatedAt:t.updatedAt,deletedAt:null},n=!0,console.log("Auth: Tenant authentication successful")):console.log("Auth: Tenant password verification failed")}else t&&console.log("Auth: Tenant found but no password hash")}catch(e){console.error("Auth: Error querying tenants table:",e)}}if(!a){console.log("Auth: User not found in users or tenants table, checking technicians table for:",e.email);try{let n=await r._.technician.findUnique({where:{email:e.email},include:{company:{include:{subscriptionPlan:!0}}}});if(console.log("Auth: Technician lookup result:",n?"Found technician":"No technician found"),n&&n.passwordHash){console.log("Auth: Technician has password hash, verifying password");let o=await s().compare(e.password,n.passwordHash);console.log("Auth: Technician password verification result:",o),o?(a={id:n.id,email:n.email,passwordHash:n.passwordHash,firstName:n.firstName,lastName:n.lastName,phone:n.phone,role:"technician",companyId:n.companyId,company:n.company,avatarUrl:n.avatarUrl,commissionRate:null,commissionDueDay:null,agreementDocument:null,emailVerified:!0,emailVerifiedAt:null,lastLoginAt:null,passwordResetToken:null,passwordResetExpires:null,preferences:{},timezone:"Africa/Kampala",createdAt:n.createdAt,updatedAt:n.updatedAt,deletedAt:null},t=!0,console.log("Auth: Technician authentication successful")):console.log("Auth: Technician password verification failed")}else n&&console.log("Auth: Technician found but no password hash")}catch(e){console.error("Auth: Error querying technicians table:",e)}}if(!a||!a.passwordHash)return console.log("Auth: No user found or no password hash"),null;if(!n&&!await s().compare(e.password,a.passwordHash))return null;return n||t||await r._.user.update({where:{id:a.id},data:{lastLoginAt:new Date}}),console.log("Auth: User company data:",{userId:a.id,companyId:a.companyId,company:a.company,isTenant:n}),{id:a.id,email:a.email,name:`${a.firstName||""} ${a.lastName||""}`.trim(),role:a.role,companyId:a.companyId,company:a.company,firstName:a.firstName,lastName:a.lastName,phone:a.phone,avatarUrl:a.avatarUrl,commissionRate:a.commissionRate,commissionDueDay:a.commissionDueDay,isTenant:n,isTechnician:t}}catch(e){return console.error("Auth error:",e),console.log("Auth: Authentication failed due to error"),null}}})],session:{strategy:"jwt",maxAge:2592e3},jwt:{maxAge:2592e3},callbacks:{jwt:async({token:e,user:a})=>(a&&(e.role=a.role,e.companyId=a.companyId,e.company=a.company,e.firstName=a.firstName,e.lastName=a.lastName,e.phone=a.phone,e.avatarUrl=a.avatarUrl,e.commissionRate=a.commissionRate,e.commissionDueDay=a.commissionDueDay,e.isTenant=a.isTenant,e.isTechnician=a.isTechnician),e),session:async({session:e,token:a})=>(a&&(e.user.id=a.sub,e.user.role=a.role,e.user.companyId=a.companyId,e.user.company=a.company,e.user.firstName=a.firstName,e.user.lastName=a.lastName,e.user.phone=a.phone,e.user.avatarUrl=a.avatarUrl,e.user.commissionRate=a.commissionRate,e.user.commissionDueDay=a.commissionDueDay,e.user.isTenant=a.isTenant,e.user.isTechnician=a.isTechnician,console.log("Auth Session Callback: companyId =",a.companyId)),e)},pages:{signIn:"/auth/login"},secret:process.env.NEXTAUTH_SECRET};async function l(e){return s().hash(e,12)}async function c(e,a){return s().compare(e,a)}},82208:(e,a,n)=>{n.d(a,{_:()=>o});var t=n(53524);let o=globalThis.prisma??new t.PrismaClient({log:["error"]})}};var a=require("../../../../webpack-runtime.js");a.C(e);var n=e=>a(a.s=e),t=a.X(0,[7787,9121,4833,7642],()=>n(68545));module.exports=t})();