// Uploads the email logo to the public brand bucket (AWS_S3_PUBLIC_BUCKET, default
// "blenaxis-public-assets") at brand/blenaxis-logo-email.png. The email templates link to that
// URL directly, so replacing the file updates every email. Run after changing the logo:
//   npm run storage:upload-brand
// Create that bucket first with `npm run storage:create-public-bucket`.
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
import { env } from '../src/config/env.js';

const KEY = 'brand/blenaxis-logo-email.png';
const bucket = env.AWS_S3_PUBLIC_BUCKET;
if (!env.AWS_REGION || !env.AWS_ACCESS_KEY_ID || !env.AWS_SECRET_ACCESS_KEY || !bucket) {
  console.error('Set AWS_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_S3_PUBLIC_BUCKET first.');
  process.exit(1);
}

const s3 = new S3Client({
  region: env.AWS_REGION,
  credentials: { accessKeyId: env.AWS_ACCESS_KEY_ID, secretAccessKey: env.AWS_SECRET_ACCESS_KEY },
});
const logo = await readFile(path.resolve(import.meta.dirname, '../assets/brand/blenaxis-logo-email.png'));
await s3.send(new PutObjectCommand({
  Bucket: bucket, Key: KEY, Body: logo, ContentType: 'image/png', CacheControl: 'public, max-age=86400',
}));
const url = `https://${bucket}.s3.${env.AWS_REGION}.amazonaws.com/${KEY}`;
console.log(`Uploaded ${KEY} to ${bucket}: ${url}`);

const response = await fetch(url, { method: 'HEAD' });
console.log(response.ok ? 'It is publicly readable, so emails will show it.' : `Not publicly readable (HTTP ${response.status}): check the bucket policy.`);
