import { S3Client, GetObjectCommand, HeadObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

const REGION = process.env.AWS_REGION || "eu-west-3";
const BUCKET = (process.env.AWS_S3_BUCKET || "odentas-docs").trim(); // Supprimer les espaces/nouvelles lignes

export const s3Client = new S3Client({
  region: REGION,
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
  },
});

export async function getS3SignedUrl(key: string, expiresInSeconds = 3600): Promise<string> {
  console.log('🔍 [S3 DEBUG] getS3SignedUrl called with:', {
    key,
    expiresInSeconds,
    region: REGION,
    bucket: BUCKET,
    hasAccessKey: !!process.env.AWS_ACCESS_KEY_ID,
    hasSecretKey: !!process.env.AWS_SECRET_ACCESS_KEY,
    accessKeyLength: process.env.AWS_ACCESS_KEY_ID?.length,
    isProduction: process.env.NODE_ENV === 'production'
  });

  const command = new GetObjectCommand({
    Bucket: BUCKET,
    Key: key,
  });
  
  try {
    const signedUrl = await getSignedUrl(s3Client, command, { expiresIn: expiresInSeconds });
    console.log('✅ [S3 DEBUG] Signed URL generated successfully for key:', key);
    return signedUrl;
  } catch (error) {
    console.error('❌ [S3 DEBUG] Error generating signed URL:', error);
    throw error;
  }
}

/**
 * Vérifie l'existence d'un objet S3 et retourne true si présent.
 */
export async function s3ObjectExists(key: string): Promise<boolean> {
  console.log('🔍 [S3 DEBUG] Checking if object exists:', key);
  try {
    const cmd = new HeadObjectCommand({ Bucket: BUCKET, Key: key });
    await s3Client.send(cmd);
    console.log('✅ [S3 DEBUG] Object exists:', key);
    return true;
  } catch (err: any) {
    console.log('❌ [S3 DEBUG] Object does not exist or error:', key, err.name);
    // Si l'erreur est NotFound (404) ou NoSuchKey, considérer comme absent
    return false;
  }
}

/**
 * Obtient une URL présignée seulement si l'objet existe. Retourne null sinon.
 */
export async function getS3SignedUrlIfExists(key: string, expiresInSeconds = 3600): Promise<string | null> {
  if (!key) return null;
  const exists = await s3ObjectExists(key);
  if (!exists) return null;
  return getS3SignedUrl(key, expiresInSeconds);
}
