/***********************************************************************************************************
 * Name         : CustomFilesRelatedListController
 * Purpose      : Apex methods for customFilesRelatedList lwc
 **********************************************************************************************************/
public with sharing class CustomFilesRelatedListController {
    /**
     * @description Returns the attachments related to a specific record
     * @param  parentId   Parent Id to get the attachments from
     * @return List of AttachmentWrapper
     */
    @AuraEnabled
    public static List<AttachmentWrapper> getAttachments(String parentId) {
        List<AttachmentWrapper> attWrappers = new List<AttachmentWrapper>();
        try {
            for (Attachment att : [
                SELECT Name, CreatedDate, BodyLength, CreatedBy.Name
                FROM Attachment
                WHERE ParentId = :parentId
                ORDER BY Name DESC
            ]) {
                attWrappers.add(
                    new AttachmentWrapper(att.Id, att.Name, att.CreatedDate, att.createdBy.Name, att.BodyLength)
                );
            }
            return attWrappers;
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }

    public class AttachmentWrapper {
        @AuraEnabled
        public String createdDate;
        @AuraEnabled
        public String name;
        @AuraEnabled
        public String createdBy;
        @AuraEnabled
        public String size;
        @AuraEnabled
        public String id;

        public AttachmentWrapper(String id, String name, Datetime createdDate, String createdBy, Integer size) {
            this.id = id;
            this.name = name;
            this.createdDate = createdDate.format();
            this.createdBy = createdBy;
            this.size = FormatUtils.formatSizeFromBytes(size);
        }
    }
}
