//  AccessItemAPIClient.mm

#import "AccessItemAPIClient.h"

@implementation AccessItemAPIClient

+ (void)fetchAccessItem:(NSString *)unitId
                        completion:(void(^)(BOOL success, NSDictionary * _Nullable response, NSError * _Nullable error))completion {

    NSString *urlString = @"https://kitadev.commudesk.com/api/owner/plan/getAccessItem?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImF0aGlyYWh6YWlkaUBjb252ZXAuY29tIiwicGFzc3dvcmQiOiIkMnkkMTAkNU9xYklqMnZ6UHJwckJrcVd5c3I2LmJCc1hVYS9Hd014eUhnL3RhUUhPUkNQcGdmTG8yakciLCJzdWIiOjIxNzAsImlzcyI6Imh0dHBzOi8va2l0YWRldi5jb21tdWRlc2suY29tL2FwaS9vd25lci9hdXRoL3Bhc3N3b3JkbGVzc19sb2dpbiIsImlhdCI6MTc2MDMxNTM1MiwiZXhwIjoyMDc1ODg0ODcyLCJuYmYiOjE3NjAzMTUzNTIsImp0aSI6IktoQmNyQnJEdDVNdDZlWmMifQ.JnxGbZ7hTeoOr6oibIzZMphgyKtTo2Aq9Efx6mrGfFA";
    NSURL *url = [NSURL URLWithString:urlString];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    NSDictionary *deviceInfo = @{
        @"OS": @"AND",
        @"IMEI": @"AND:2a2f13ff17b1cbb5",
        @"OS_VERSION": @"35",
        @"MODEL": @"2306EPN60G",
        @"APP_VERSION": @"1.22.26"
    };

    NSDictionary *jsonBody = @{
        @"data": @{
            @"os": @"AND",
            @"drawing_plan_id": unitId ?: @"",
            @"information": deviceInfo,
        }
    };
  
    NSLog(@"🌍 SUBMIT URL: %@", urlString);
    NSLog(@"📦 SUBMIT Body JSON: %@", jsonBody);
    
    NSError *jsonError;
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:jsonBody options:0 error:&jsonError];

    if (jsonError) {
        NSLog(@"❌ JSON Serialization Error: %@", jsonError);
        if (completion) completion(NO, nil, jsonError);
        return;
    }

    request.HTTPBody = bodyData;

    NSLog(@"🔄 SUBMIT (NO REP) Request started...");

    NSURLSessionDataTask *task = [[NSURLSession sharedSession]
        dataTaskWithRequest:request
          completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        if (error) {
            NSLog(@"❌ Network Error: %@", error);
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(NO, nil, error);
            });
            return;
        }

        NSError *parseError;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];

        if (parseError) {
            NSLog(@"⚠️ JSON Parse Error: %@", parseError);
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(NO, nil, parseError);
            });
            return;
        }

        NSLog(@"✅ SUBMIT (NO REP) API Response:\n%@", json);

        dispatch_async(dispatch_get_main_queue(), ^{
            completion(YES, json, nil);
        });
    }];

    [task resume];
}

@end
