#import <React/RCTBridgeModule.h>
#import <React/RCTLog.h>
#import <React/RCTBridge.h>

@interface RCT_EXTERN_MODULE(CodePush, NSObject)

RCT_EXTERN_METHOD(downloadUpdate:(NSString *)url outputPath:(NSString *)outputPath callback:(RCTResponseSenderBlock)callback)
RCT_EXTERN_METHOD(applyUpdate:(NSString *)filePath callback:(RCTResponseSenderBlock)callback)

@end

@implementation CodePush

// Method to download the update (same as before)
RCT_EXPORT_METHOD(downloadUpdate:(NSString *)url outputPath:(NSString *)outputPath callback:(RCTResponseSenderBlock)callback)
{
        // Create a URL from the provided URL string
    NSURL *downloadURL = [NSURL URLWithString:url];
    
    if (!downloadURL) {
        callback(@[@"Invalid URL"]);
        return;
    }

    // Create a destination path for saving the update
    NSURL *destinationURL = [NSURL fileURLWithPath:outputPath];

    // Create a URL session for downloading the file
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:downloadURL completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
        
        if (error) {
            callback(@[@"Download failed", error.localizedDescription]);
            return;
        }
        
        // Move the downloaded file to the desired destination
        NSError *fileError;
        [[NSFileManager defaultManager] moveItemAtURL:location toURL:destinationURL error:&fileError];
        
        if (fileError) {
            callback(@[@"Failed to move file", fileError.localizedDescription]);
        } else {
            callback(@[@"Download successful"]);
        }
    }];
    
    // Start the download
    [downloadTask resume];
}

// Apply the downloaded update
RCT_EXPORT_METHOD(applyUpdate:(NSString *)filePath callback:(RCTResponseSenderBlock)callback)
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSString *bundlePath = filePath; // Path to the downloaded bundle

    if ([fileManager fileExistsAtPath:bundlePath]) {
        // Assuming the downloaded bundle is valid, we replace the current JS bundle with the new one
        // Set the new bundle path in the bridge
        // You might need to update the bundle file path for the JS code that gets loaded.

        // Reload JS bundle or restart the app
        RCTBridge *bridge = [UIApplication sharedApplication].delegate.window.rootViewController.bridge;
        [bridge reload];

        callback(@[@"Update applied and app reloaded."]);
    } else {
        callback(@[@"Error: File not found."]);
    }
}

@end