import { Types } from 'mongoose';

import { PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { v4 as uuidv4 } from 'uuid';
import config from '@/shared/config/config';
import { R2Client } from '@/shared/constants/r2service.constant';

interface GeneratePresignedUrlParams {
  companyId: Types.ObjectId;
  folderName: string;
  schema?: string;
  fileName: string;
  subType?: string;
  userId?: string;
  contentType: string; // 'image/jpeg', 'video/mp4', etc.
}

interface PresignedUrlResponse {
  url: string;
  key: string;
  id: string;
}

export const generatePresignedUrl = async ({
  companyId,
  schema,
  fileName,
  userId,
  contentType,
}: GeneratePresignedUrlParams): Promise<PresignedUrlResponse | undefined> => {
  const bucketName = config.r2.bucketName;
  const id = uuidv4();

  let key: string = `${companyId}/${schema}/${userId}/${fileName}`;

  try {
    const command = new PutObjectCommand({
      Bucket: bucketName,
      Key: key,
      ContentType: contentType,
    });

    const url = await getSignedUrl(R2Client, command, {
      expiresIn: 60 * 60 * 1, // 1 hour
    });

    return { url, key, id };
  } catch (err) {
    console.error('Error generating pre-signed URL:', err);
    return;
  }
};
