//
//  SnapmintEventEmitter.m
//  IndusBitTest
//
//  Created by IndusBit Team
//  Copyright © 2023 IndusBit. All rights reserved.
//

#import "SnapmintEventEmitter.h"

@implementation SnapmintEventEmitter

static SnapmintEventEmitter *sharedInstance = nil;

RCT_EXPORT_MODULE()

+ (id)allocWithZone:(NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [super allocWithZone:zone];
    });
    return sharedInstance;
}

+ (SnapmintEventEmitter *)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (NSArray<NSString *> *)supportedEvents {
    return @[@"Snapmint::PAYMENT_SUCCESS", @"Snapmint::PAYMENT_ERROR"];
}

+ (void)onPaymentSuccess:(NSString *)paymentId andData:(NSDictionary *)response {
    NSLog(@"📡 [SnapmintEventEmitter] Emitting payment success event");
    
    NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary:response ?: @{}];
    
    // Ensure required fields
    if (paymentId) {
        data[@"paymentId"] = paymentId;
    }
    data[@"status"] = @"success";
    data[@"statusCode"] = @200;
    data[@"timestamp"] = [NSDateFormatter localizedStringFromDate:[NSDate date]
                                                        dateStyle:NSDateFormatterFullStyle
                                                        timeStyle:NSDateFormatterFullStyle];
    
    [[SnapmintEventEmitter sharedInstance] sendEventWithName:@"Snapmint::PAYMENT_SUCCESS" body:data];
}

+ (void)onPaymentError:(int)code description:(NSString *)description andData:(NSDictionary *)response {
    NSLog(@"📡 [SnapmintEventEmitter] Emitting payment error event");
    
    NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary:response ?: @{}];
    
    // Ensure required fields
    data[@"status"] = @"failure";
    data[@"statusCode"] = @(code);
    data[@"message"] = description ?: @"Payment failed";
    data[@"responseMsg"] = description ?: @"Payment failed";
    data[@"timestamp"] = [NSDateFormatter localizedStringFromDate:[NSDate date]
                                                        dateStyle:NSDateFormatterFullStyle
                                                        timeStyle:NSDateFormatterFullStyle];
    
    [[SnapmintEventEmitter sharedInstance] sendEventWithName:@"Snapmint::PAYMENT_ERROR" body:data];
}

// Required for RCTEventEmitter
+ (BOOL)requiresMainQueueSetup {
    return YES;
}

@end