//
//  SnapmintEventEmitter.m
//  SnapmintTest
//
//  Created by Snapmint Team
//

#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;
    }
    // Mirror Flutter: include status, statusCode=200 and responseMsg if message/data present
    data[@"status"] = @"success";
    data[@"statusCode"] = @200;
    // Normalize data to string like Android
    id payload = data[@"data"];
    if ([payload isKindOfClass:[NSDictionary class]] || [payload isKindOfClass:[NSArray class]]) {
        NSError *err = nil;
        NSData *json = [NSJSONSerialization dataWithJSONObject:payload options:0 error:&err];
        if (json && !err) {
            NSString *jsonStr = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
            data[@"data"] = jsonStr;
            if (!data[@"responseMsg"]) { data[@"responseMsg"] = jsonStr; }
        }
    } else if ([payload isKindOfClass:[NSString class]]) {
        if (!data[@"responseMsg"]) { data[@"responseMsg"] = (NSString *)payload; }
    } else if (!data[@"responseMsg"]) {
        id msg = data[@"message"];
        if ([msg isKindOfClass:[NSString class]]) { data[@"responseMsg"] = (NSString *)msg; }
    }
    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");
    NSLog(@"📡 [SnapmintEventEmitter] ERROR CODE=%d DESC=%@ DATA=%@", code, description, response);
    
    NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary:response ?: @{}];
    
    // Ensure required fields
    data[@"status"] = @"failure";
    data[@"statusCode"] = @(code);
    data[@"message"] = description ?: @"Payment failed";
    
    // Set responseMsg: prefer description, then message from response, then data payload
    NSString *responseMessage = description;
    if (!responseMessage || [responseMessage length] == 0) {
        responseMessage = data[@"message"] ?: data[@"responseMsg"];
    }
    
    // Normalize data payload to string like Android
    id payload = data[@"data"];
    if ([payload isKindOfClass:[NSDictionary class]] || [payload isKindOfClass:[NSArray class]]) {
        NSError *err = nil;
        NSData *json = [NSJSONSerialization dataWithJSONObject:payload options:0 error:&err];
        if (json && !err) {
            NSString *jsonStr = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
            data[@"data"] = jsonStr;
        }
    } else if ([payload isKindOfClass:[NSString class]] && [(NSString *)payload length] == 0) {
        // Empty string data, don't use it for responseMsg
        payload = nil;
    }
    
    // Set responseMsg: use responseMessage if available, else use data payload if non-empty
    if (responseMessage && [responseMessage length] > 0) {
        data[@"responseMsg"] = responseMessage;
    } else if ([payload isKindOfClass:[NSString class]] && [(NSString *)payload length] > 0) {
        data[@"responseMsg"] = (NSString *)payload;
    } else {
        data[@"responseMsg"] = @"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