const { deleteFile } = require('../helpers');

const uploadFolders = {
  selfieImg: 'host-uploads',
  supportingDocs: 'host-uploads',
  listingImgs: 'host-uploads',
  profileImg: 'user-uploads',
  validIdImg: 'user-uploads',
  messageAttachments: 'convo-uploads',
  travelersPhoto: 'user-uploads',
  governmentId: 'user-uploads',
};

exports.handleFiles = (files, userId, supportingDocTypes, listingImageCategories) => {
  const fileRecords = [];

  if (files.listingImgs && files.listingImgs.length > 0) {
    const listingImgRecords = files.listingImgs.map((file, index) => ({
      listing_id: userId,
      file_type: 'Listing Images',
      name: listingImageCategories?.[index],
      file: file.filename,
    }));
    fileRecords.push(...listingImgRecords);
  }

  if (files.supportingDocs && files.supportingDocs.length > 0) {
    const supportingDocRecords = files.supportingDocs.map((file, index) => ({
      listing_id: userId,
      file_type: 'Supporting Documents',
      name: supportingDocTypes?.[index],
      file: file.filename,
    }));
    fileRecords.push(...supportingDocRecords);
  }

  return fileRecords;
};

exports.deleteUploadedFiles = (req) => {
  for (const key in req.files) {
    if (req.files[key] && req.files[key].length > 0) {
      for (const file of req.files[key]) {
        deleteFile(file.filename, uploadFolders[key]);
      }
    }
  }
};

exports.getFileType = (mimetype) => {
  if (!mimetype) return 'file';

  if (mimetype.startsWith('image/')) {
    return 'image';
  }

  if (mimetype === 'application/pdf') {
    return 'pdf';
  }

  return 'file';
};
