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

static NSString *kBaseURL = @"https://kitadev.commudesk.com/api";
static NSString *kDrawingPlanId = @"";
static NSString *kProjectId = @"";
static NSString *kAuthToken = @"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImF0aGlyYWh6YWlkaUBjb252ZXAuY29tIiwicGFzc3dvcmQiOiIkMnkkMTAkNU9xYklqMnZ6UHJwckJrcVd5c3I2LmJCc1hVYS9Hd014eUhnL3RhUUhPUkNQcGdmTG8yakciLCJzdWIiOjIxNzAsImlzcyI6Imh0dHBzOi8va2l0YWRldi5jb21tdWRlc2suY29tL2FwaS9vd25lci9hdXRoL3Bhc3N3b3JkbGVzc19sb2dpbiIsImlhdCI6MTc2MDMxNTM1MiwiZXhwIjoyMDc1ODg0ODcyLCJuYmYiOjE3NjAzMTUzNTIsImp0aSI6IktoQmNyQnJEdDVNdDZlWmMifQ.JnxGbZ7hTeoOr6oibIzZMphgyKtTo2Aq9Efx6mrGfFA";

@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 - 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);
    }
}

+ (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
