const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');
const crypto = require('crypto');
const express = require('express');
const fs = require('fs');
const multer = require('multer');
const path = require('path');
require('dotenv').config()

const app = express();
const port = 3000;

// Configure AWS
const s3Client = new S3Client({
  region: process.env.AWS_REGION,
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY,
    secretAccessKey: process.env.AWS_SECRET_KEY
  }
});

const upload = multer({ dest: 'uploads/' });

// POST endpoint to upload an image
app.post('/image', upload.single('image'), (req, res) => {
  const file = req.file;

  // Read the file from the temporary location
  fs.readFile(file.path, async (err, data) => {
    if (err) throw err; // Handle error

    const hashSum = crypto.createHash('sha256');
    hashSum.update(data);
    const hashHex = hashSum.digest('hex');

    const bucketName = 'gifts-image';
    const fileName = `${hashHex}_${file.originalname}`;
    const params = {
      Body: data,
      Bucket: bucketName, // S3 Bucket name
      ContentType: file.mimetype, // File content type
      Key: fileName, // File name to use in S3
    };

    // Upload the file to S3
    try {
      const command = new PutObjectCommand(params);
      const response = await s3Client.send(command);
      const finalUrl = `https://${bucketName}.s3.amazonaws.com/${fileName}`;
      res.send(JSON.stringify({ success: true, url: finalUrl }));
    } catch (uploadError) {
      console.error('Error uploading to S3:', uploadError);
      res.status(500).send(JSON.stringify({ success: false, message: 'Error uploading file.' }));
    }
  });
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});