//  SyncPendingShareHelper.mm
#import "SyncPendingShareHelper.h"
#import <CommonCrypto/CommonCryptor.h>
#import <MessageUI/MessageUI.h>

@interface SyncPendingShareHelper () <MFMailComposeViewControllerDelegate>
@property (nonatomic, weak) UIViewController *presentingController;
@end

@implementation SyncPendingShareHelper

+ (void)sharePendingItems:(NSArray<NSDictionary *> *)items
           fromController:(UIViewController *)controller {
    if (!items || items.count == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"No Data"
                                                                       message:@"There are no pending items to share."
                                                                preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
        [controller presentViewController:alert animated:YES completion:nil];
        return;
    }

    SyncPendingShareHelper *helper = [SyncPendingShareHelper new];
    helper.presentingController = controller;
    [helper prepareAndShareItems:items];
}

- (void)prepareAndShareItems:(NSArray<NSDictionary *> *)items {
    NSError *error = nil;

    // Paths
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *issueFile = [documentsPath stringByAppendingPathComponent:@"all_pending_issue_data.txt"];
    NSString *encryptFile = [documentsPath stringByAppendingPathComponent:@"all_pending_issue_data_encrypt.txt"];

    // Write JSON
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:items options:NSJSONWritingPrettyPrinted error:&error];
    if (error) { NSLog(@"JSON Serialization error: %@", error); return; }
    [jsonData writeToFile:issueFile atomically:YES];

    // AES-128-CBC Encryption
    NSString *keyString = @"mySecretKey12345"; // 16 chars
    NSData *keyData = [keyString dataUsingEncoding:NSUTF8StringEncoding];
    NSData *dataToEncrypt = jsonData;

    uint8_t ivBytes[kCCBlockSizeAES128];
    if (SecRandomCopyBytes(kSecRandomDefault, kCCBlockSizeAES128, ivBytes) != errSecSuccess) { NSLog(@"Failed IV"); return; }
    NSData *ivData = [NSData dataWithBytes:ivBytes length:kCCBlockSizeAES128];

    size_t outLength;
    NSMutableData *cipherData = [NSMutableData dataWithLength:dataToEncrypt.length + kCCBlockSizeAES128];

    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding,
                                          keyData.bytes,
                                          kCCKeySizeAES128,
                                          ivData.bytes,
                                          dataToEncrypt.bytes,
                                          dataToEncrypt.length,
                                          cipherData.mutableBytes,
                                          cipherData.length,
                                          &outLength);

    if (cryptStatus != kCCSuccess) { NSLog(@"Encryption failed: %d", cryptStatus); return; }
    cipherData.length = outLength;

    NSString *ivBase64 = [ivData base64EncodedStringWithOptions:0];
    NSString *cipherBase64 = [cipherData base64EncodedStringWithOptions:0];
    NSString *finalEncryptedString = [NSString stringWithFormat:@"%@:%@", ivBase64, cipherBase64];

    [finalEncryptedString writeToFile:encryptFile atomically:YES encoding:NSUTF8StringEncoding error:&error];
    if (error) { NSLog(@"Failed to write encrypted file: %@", error); return; }

    // Present Mail
    if ([MFMailComposeViewController canSendMail]) {
        MFMailComposeViewController *mailVC = [[MFMailComposeViewController alloc] init];
        mailVC.mailComposeDelegate = self;
        [mailVC setSubject:@"QMS Owner - Sync Troubleshoot Log"];
        [mailVC setToRecipients:@[@"support@convep.com"]];
        [mailVC setMessageBody:@"Attached are the log file and encrypted data for reference." isHTML:NO];

        NSData *issueData = [NSData dataWithContentsOfFile:issueFile];
        NSData *encryptData = [NSData dataWithContentsOfFile:encryptFile];

        [mailVC addAttachmentData:issueData mimeType:@"text/plain" fileName:@"all_pending_issue_data.txt"];
        [mailVC addAttachmentData:encryptData mimeType:@"text/plain" fileName:@"all_pending_issue_data_encrypt.txt"];

        [self.presentingController presentViewController:mailVC animated:YES completion:nil];
    } else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error"
                                                                       message:@"Mail services are not available."
                                                                preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
        [self.presentingController presentViewController:alert animated:YES completion:nil];
    }
}

// Mail delegate
- (void)mailComposeController:(MFMailComposeViewController *)controller
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError *)error {
    [controller dismissViewControllerAnimated:YES completion:nil];
    if (error) NSLog(@"Mail send error: %@", error);
}

@end
