import { createRequire } from 'module'; const require = createRequire(import.meta.url);
import{DynamoDBClient as N,PutItemCommand as E}from"@aws-sdk/client-dynamodb";var u=new N({});async function v(r){console.log("Processing SMS event from SQS:",JSON.stringify(r,null,2));let a=process.env.TABLE_NAME;if(!a)throw new Error("TABLE_NAME environment variable not set");let i=Number.parseInt(process.env.RETENTION_DAYS||"90",10);for(let m of r.Records)try{let e=JSON.parse(m.body),t=e.eventType||e.messageStatus||"UNKNOWN",n=e.messageId,d=e.destinationPhoneNumber,c=e.originationPhoneNumber,o=e.messageBody||"",T=e.isoCountryCode||"US",S=e.messageType||"TRANSACTIONAL",p=e.eventTimestamp?new Date(e.eventTimestamp).getTime():Date.now();console.log("Processing SMS event:",{messageId:n,eventType:t,destinationNumber:d,originationNumber:c});let s={isoCountryCode:T,messageType:S};t==="TEXT_DELIVERED"||t==="TEXT_SUCCESSFUL"?s={...s,deliveryTimestamp:e.deliveryTimestamp,carrierName:e.carrierName,providerResponse:e.providerResponse}:t==="TEXT_FAILED"||t==="TEXT_INVALID"||t==="TEXT_CARRIER_UNREACHABLE"||t==="TEXT_BLOCKED"?s={...s,failureReason:e.failureReason||e.statusMessage,failureCode:e.failureCode||e.statusCode,providerResponse:e.providerResponse}:t==="TEXT_QUEUED"||t==="TEXT_SENT"?s={...s,queuedTimestamp:e.queuedTimestamp,sentTimestamp:e.sentTimestamp}:t==="TEXT_TTL_EXPIRED"&&(s={...s,expirationTimestamp:e.expirationTimestamp,ttlSeconds:e.ttlSeconds});let l=o?Math.ceil(o.length/160):1,g=i>0?Date.now()+i*24*60*60*1e3:Date.now()+365*24*60*60*1e3;await u.send(new E({TableName:a,Item:{messageId:{S:n},sentAt:{N:p.toString()},accountId:{S:process.env.AWS_ACCOUNT_ID||"unknown"},destinationNumber:{S:d||""},originationNumber:{S:c||""},messageBody:{S:o},eventType:{S:t},segments:{N:l.toString()},eventData:{S:JSON.stringify(e)},additionalData:{S:JSON.stringify(s)},createdAt:{N:Date.now().toString()},expiresAt:{N:g.toString()}}})),console.log(`Stored ${t} event for message ${n}`,s)}catch(e){console.error("Error processing record:",e),console.error("Record:",JSON.stringify(m,null,2))}return{statusCode:200,body:JSON.stringify({message:"SMS events processed successfully"})}}export{v as handler};
