//  APIConfig.mm
#import "APIConfig.h"
#import "LocalStorage.h"
#import "NetworkManager.h"

static NSString *kBaseURL = @"https://sptest.commudesk.com/api";
static NSString *kDrawingPlanId = @"";
static NSString *kProjectId = @"";
static NSString *kAuthToken = @"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzY29wZSI6InNlcnZlci10by1zZXJ2ZXIiLCJmcmFtZXdvcmstYXBpIjp0cnVlLCJjb21wYW55X2NvZGUiOiJTUFQiLCJzdWIiOjE1NTcsImlzcyI6Imh0dHBzOi8vc3B0ZXN0LmNvbW11ZGVzay5jb20vYXBpL2ZyYW1ld29yay9vd25lci9hdXRoL2NsaWVudF9hdXRoZW50aWNhdGlvbiIsImlhdCI6MTc2Nzc1MjU5OSwiZXhwIjoyMDgzMzIyMTE5LCJuYmYiOjE3Njc3NTI1OTksImp0aSI6IktEcmhmSXgzeWU0WmxaUEYifQ.Bv4ZSjGRm9YYOjGItLSV_3wS7grKuPTabL60BFnp88o";
static NSString *kClientId = @"1";
static NSString *kLotId = @"";

@implementation APIConfig
#pragma mark - OS
+ (NSString *)os {
    return @"AND";
}

#pragma mark - URL
+ (NSString *)baseURL {
    return kBaseURL;
}

+ (void)setBaseURL:(NSString *)baseURL {
    if (baseURL.length > 0) {
        kBaseURL = [baseURL copy];
        NSLog(@"🌐 API baseURL set to: %@", kBaseURL);
    }
}

#pragma mark - Client Id
+ (NSString *)clientId {
    return kClientId;
}

+ (void)setClientId:(NSString *)clientId {
    if (clientId.length > 0) {
        kClientId = [clientId copy];
        NSLog(@"🌐 API baseURL set to: %@", kClientId);
    }
}

#pragma mark - Project Id
+ (NSString *)projectId {
    return kProjectId;
}

+ (void)setProjectId:(NSString *)projectId {
    if (projectId.length > 0) {
        kProjectId = [projectId copy];
        NSLog(@"🌐 API projectId set to: %@", kProjectId);
    }
}

#pragma mark - Drawing Plan Id
+ (NSString *)drawingPlanId {
    return kDrawingPlanId;
}

+ (void)setDrawingPlanId:(NSString *)drawingPlanId {
    if (drawingPlanId.length > 0) {
        kDrawingPlanId = [drawingPlanId copy];
        NSLog(@"🌐 API drawing plan id set to: %@", kDrawingPlanId);
    }
}

#pragma mark - AuthToken
+ (NSString *)authToken {
  return kAuthToken;
}

+ (void)setAuthTokem:(NSString *)authToken {
    if (authToken.length > 0) {
        kAuthToken = [authToken copy];
        NSLog(@"🌐 API drawing plan id set to: %@", kAuthToken);
    }
}

#pragma mark - LotId
+ (NSString *)lotId {
    return kLotId;
}

+ (void)setLotId:(NSString *)lotId {
    if (lotId.length > 0) {
        kLotId = [lotId copy];
        NSLog(@"🌐 API lotId set to: %@", kLotId);
    }
}

+ (NSURL *)urlWithPath:(NSString *)path {
    NSString *urlString =
        [NSString stringWithFormat:@"%@%@?token=%@",
         [self baseURL],
         path,
         [self authToken]];
    return [NSURL URLWithString:urlString];
}

+ (NSDictionary<NSString *, NSString *> *)deviceInfo {
    return @{
        @"OS": [self os],
        @"drawing_plan_id": [self drawingPlanId],
        @"IMEI": @"AND:2a2f13ff17b1cbb5",
        @"OS_VERSION": @"35",
        @"MODEL": @"2306EPN60G",
        @"APP_VERSION": @"1.22.26"
    };
}

+ (NSString *)deviceInfoJSONString {
    NSData *data =
        [NSJSONSerialization dataWithJSONObject:[self deviceInfo]
                                        options:0
                                          error:nil];

    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

#pragma mark - Offline Handling
+ (BOOL)handleOfflineForAPI:(NSString *)apiName
                 completion:(void(^)(BOOL success, NSDictionary * _Nullable response, NSError * _Nullable error))completion {

    NSString *cacheKey =
        [NSString stringWithFormat:@"%@_%@", apiName, [self projectId]];

    if (![NetworkManager.sharedManager isConnected]) {
        NSDictionary *cached = [LocalStorage loadDictionaryForKey:cacheKey];

        if (cached) {
            NSLog(@"🟡 Loaded from cache: %@", cacheKey);
            if (completion) completion(YES, cached, nil);
        } else {
            NSError *offlineErr =
                [NSError errorWithDomain:@"OfflineError"
                                    code:-1
                                userInfo:@{
                                    NSLocalizedDescriptionKey:
                                    @"No network and no cached data"
                                }];
            if (completion) completion(NO, nil, offlineErr);
        }
        return YES; // offline handled
    }

    return NO; // proceed with online request
}

#pragma mark - Null Handling
+ (NSDictionary *)dictionaryByReplacingNullsWithBlanks:(NSDictionary *)dict {
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    for (NSString *key in dict) {
        id value = dict[key];
        if (value == [NSNull null]) {
            result[key] = @""; // or NSNull-safe replacement
        } else if ([value isKindOfClass:[NSDictionary class]]) {
            result[key] = [self dictionaryByReplacingNullsWithBlanks:value];
        } else if ([value isKindOfClass:[NSArray class]]) {
            result[key] = [self arrayByReplacingNullsWithBlanks:value];
        } else {
            result[key] = value;
        }
    }
    return result;
}

+ (NSArray *)arrayByReplacingNullsWithBlanks:(NSArray *)array {
    NSMutableArray *result = [NSMutableArray array];
    for (id obj in array) {
        if (obj == [NSNull null]) {
            [result addObject:@""]; // or other safe value
        } else if ([obj isKindOfClass:[NSDictionary class]]) {
            [result addObject:[self dictionaryByReplacingNullsWithBlanks:obj]];
        } else if ([obj isKindOfClass:[NSArray class]]) {
            [result addObject:[self arrayByReplacingNullsWithBlanks:obj]];
        } else {
            [result addObject:obj];
        }
    }
    return result;
}

@end
