/***********************************************************************************************************
 * Name         : EventLogViewerHelper
 * Purpose      : Apex helper for the eventLogViewer LWC. Provides server-side data for EventLogFile
 *                and archived ContentVersion records.
 **********************************************************************************************************/
public with sharing class EventLogViewerHelper {
    /**
     * @description Returns all EventLogFile records ordered by most recent log date first.
     *  Used by the Raw Event Logs tab in the eventLogViewer LWC.
     * @return List<EventLogFile> records with Id, EventType, LogDate, and LogFileLength
     */
    @AuraEnabled(cacheable=true)
    public static List<EventLogFile> getEventLogs() {
        return [
            SELECT Id, EventType, LogDate, LogFileLength
            FROM EventLogFile
            ORDER BY LogDate DESC, EventType ASC
        ];
    }

    /**
     * @description Returns archived EventLog ContentVersion records from the configured Content Library,
     *  identified by the EventLog description marker. Used by the Archived Files tab.
     * @return List<ContentVersion> records with Id, Title, ContentDocumentId, ContentSize, CreatedDate, PathOnClient
     */
    @AuraEnabled(cacheable=true)
    public static List<ContentVersion> getArchivedLogs() {
        String libraryId = ConfigUtils.getConfigString(ConfigUtils.EVENT_LOG_ARCHIVE_LIBRARY_ID);
        if (String.isBlank(libraryId)) {
            return new List<ContentVersion>();
        }
        return [
            SELECT Id, Title, ContentDocumentId, ContentSize, CreatedDate, PathOnClient
            FROM ContentVersion
            WHERE Description = :EventLogFileArchiveBatch.EVENT_LOG
            AND ContentDocument.ParentId = :libraryId
            AND IsLatest = TRUE
            ORDER BY CreatedDate DESC
        ];
    }

    /**
     * @description Returns the LogFile content of an EventLogFile record as a base64-encoded string
     *  so the LWC can trigger a browser download without a separate authenticated request.
     * @param eventLogFileId Id of the EventLogFile record to download
     * @return String base64-encoded CSV content
     */
    @AuraEnabled
    public static String getEventLogFileContent(Id eventLogFileId) {
        EventLogFile elf = [SELECT LogFile, EventType, LogDate FROM EventLogFile WHERE Id = :eventLogFileId LIMIT 1];
        return EncodingUtil.base64Encode(elf.LogFile);
    }
}
