//
//  SnapmintCheckoutWrapper.m
//  IndusBitTest
//
//  Clean implementation using Swift factory like Razorpay pattern
//

#import "SnapmintCheckoutWrapper.h"
#import <UIKit/UIKit.h>
// auto-generated Swift header for the pod (pod name indusbit-math → indusbit_math-Swift.h)
#if __has_include("indusbit_math-Swift.h")
#import "indusbit_math-Swift.h"
#else
#error "Swift bridge header not found. Ensure USE_FRAMEWORKS! is enabled and the pod is built."
#endif

@interface SnapmintCheckoutWrapper ()
@property(nonatomic,strong) NSURL *checkoutUrl;
@property(nonatomic,copy) SnapmintCompletionBlock completion;
@end

@implementation SnapmintCheckoutWrapper

- (instancetype)initWithUrl:(NSURL *)url completion:(SnapmintCompletionBlock)completion {
    if (self = [super init]) {
        _checkoutUrl = url;
        _completion = completion;
    }
    return self;
}

- (UIViewController *)createHostingController {
    if (!self.checkoutUrl) { return [UIViewController new]; }
    if (@available(iOS 13.0, *)) {
        __weak typeof(self) weakSelf = self;
        UIViewController *vc = [SnapmintUIHostingControllerFactory hostingControllerFor:self.checkoutUrl
                                                                        resultHandler:^(id _Nullable result) {
            if (!weakSelf.completion) { return; }
            NSString *status = [result valueForKey:@"status"] ?: @"unknown";
            NSString *message = [result valueForKey:@"message"] ?: @"No message";
            NSDictionary *resultDict = @{ @"status": status,
                                          @"message": message,
                                          @"responseMsg": message,
                                          @"timestamp": [NSDateFormatter localizedStringFromDate:[NSDate date]
                                                                                           dateStyle:NSDateFormatterFullStyle
                                                                                           timeStyle:NSDateFormatterFullStyle] };
            BOOL ok = [status.lowercaseString isEqualToString:@"success"] ||
                      [status.lowercaseString isEqualToString:@"completed"] ||
                      [status.lowercaseString isEqualToString:@"paid"];
            if (ok) {
                weakSelf.completion(resultDict, nil);
            } else {
                weakSelf.completion(nil, message);
            }
        }];
        return vc ?: [UIViewController new];
    }
    // Fallback < iOS13
    if (self.completion) {
        self.completion(nil, @"iOS 13.0+ required for Snapmint checkout");
    }
    return [UIViewController new];
}

@end