import { CloudWatchLogsClient, CreateLogStreamCommand, PutLogEventsCommand } from "@aws-sdk/client-cloudwatch-logs"; // ES Modules import

const client = new CloudWatchLogsClient({ region: process.env.AWS_REGION });
const logGroupName = process.env.LOG_GROUP_NAME;

export const handler = async (event, context) => {
  const logStreamName = Math.random().toString(32).substring(2);
  let message;

  const params = {
    logGroupName,
    logStreamName,
    logEvents: [
      {
        timestamp: Date.now(),
        message,
      },
    ],
  };
  try {
    await client.send(new CreateLogStreamCommand({ logGroupName, logStreamName }));
    console.log(`Log stream ${logStreamName} created.`);
    event.Records.forEach(async function (record) {
      params.logEvents[0].message = Buffer.from(record.kinesis.data, "base64").toString("ascii");
      await client.send(new PutLogEventsCommand(params));
    });
  } catch (err) {
    console.error(err);
    throw new Error(err);
  }
  return { statusCode: 200, body: "Log sent to CloudWatch" };
};
