const { S3Client, PutBucketPolicyCommand } = require("@aws-sdk/client-s3");

const client = new S3Client({
  endpoint: process.env.S3_ENDPOINT,
  region: process.env.S3_REGION || "eu-2",
  credentials: {
    accessKeyId: process.env.S3_ACCESS_KEY_ID,
    secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
  },
  forcePathStyle: true,
});

const bucket = process.env.S3_BUCKET_NAME || "monuments-images";

const policy = {
  Version: "2012-10-17",
  Statement: [
    {
      Sid: "PublicReadGetObject",
      Effect: "Allow",
      Principal: { AWS: ["*"] },
      Action: ["s3:GetObject"],
      Resource: [`arn:aws:s3:::${bucket}/*`],
    },
  ],
};

client
  .send(new PutBucketPolicyCommand({ Bucket: bucket, Policy: JSON.stringify(policy) }))
  .then(() => console.log("Bucket policy set successfully:", bucket))
  .catch((err) => {
    console.error("Failed to set bucket policy:", err.message);
    process.exit(1);
  });