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

const useR2 = process.env.R2_BUCKET && process.env.R2_ACCESS_KEY_ID && process.env.R2_SECRET_ACCESS_KEY && process.env.R2_ENDPOINT;
let s3;
if (useR2) {
  s3 = new S3Client({
    region: 'auto',
    endpoint: process.env.R2_ENDPOINT,
    credentials: {
      accessKeyId: process.env.R2_ACCESS_KEY_ID,
      secretAccessKey: process.env.R2_SECRET_ACCESS_KEY,
    },
  });
}

async function uploadLocal(filePathRel) {
  const fullPath = path.join(process.cwd(), config.uploadDir, filePathRel);
  const url = `${config.baseUrl}/uploads/${filePathRel.replace(/\\/g, '/')}`;
  return { url, path: filePathRel };
}

async function uploadR2(fileBuffer, key, contentType = 'image/jpeg') {
  const bucket = process.env.R2_BUCKET;
  await s3.send(new PutObjectCommand({ Bucket: bucket, Key: key, Body: fileBuffer, ContentType: contentType }));
  const publicUrlBase = process.env.R2_PUBLIC_URL_BASE || `${process.env.R2_ENDPOINT}/${bucket}`;
  const url = `${publicUrlBase}/${key}`;
  return { url, path: key };
}

function formatDateForFilename() {
  const now = new Date();
  const day = String(now.getDate()).padStart(2, '0');
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const year = now.getFullYear();
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  return `day-${day}-${month}-${year}-${hours}-${minutes}-${seconds}`;
}

module.exports = {
  /**
   * Upload from a local file saved by Multer. If R2 configured, re-upload to R2 and return its URL; else return local URL.
   */
  async uploadSelfie(localDiskPath, userName = 'unknown') {
    const ext = path.extname(localDiskPath) || '.jpg';
    const formattedDate = formatDateForFilename();
    const fileName = `${formattedDate}${ext}`;
    
    if (useR2) {
      const fileBuffer = fs.readFileSync(localDiskPath);
      // Create folder structure: attendance_app/{userName}/
      const key = `attendance_app/${userName}/${fileName}`;
      return await uploadR2(fileBuffer, key, 'image/jpeg');
    }
    const rel = path.join('selfies', fileName);
    return await uploadLocal(rel);
  },
};
