// Base Connection Configuration
// Intune Data Warehouse API Base URL and Headers

let
    // Base URL for Intune Data Warehouse API
    BaseUrl = "https://fef.msua01.manage.microsoft.com/ReportingService/DataWarehouseFEService?api-version=v1.0",
    
    // Standard JSON headers for API requests
    JsonHeaders = [
        #"Accept" = "application/json",
        #"Content-Type" = "application/json",
        #"User-Agent" = "PowerBI-IntuneDataWarehouse/1.0"
    ],
    
    // Helper function for handling paginated API responses
    GetPaged = (Endpoint as text) as table =>
        let
            // Construct full URL
            InitialUrl = BaseUrl & Endpoint,
            
            // Function to get a single page of data
            GetPage = (url as text) =>
                let
                    // Make web request with error handling
                    Raw = Web.Contents(
                        url,
                        [
                            Headers = JsonHeaders,
                            ManualStatusHandling = {400, 401, 403, 404, 429, 500, 503}
                        ]
                    ),
                    
                    // Parse JSON response
                    Parsed = Json.Document(Raw),
                    
                    // Extract data and next link
                    Value = if Record.HasFields(Parsed, "value") then Parsed[value] else {},
                    NextLink = if Record.HasFields(Parsed, "@odata.nextLink") then Parsed[@odata.nextLink] else null,
                    
                    // Convert to table
                    Tbl = Table.FromList(Value, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
                    
                    // Handle empty results
                    Res = if Tbl <> null and not Table.IsEmpty(Tbl) then Tbl else #table({}, {})
                in
                    [Rows = Res, Next = NextLink],
            
            // Loop through all pages
            Loop = List.Generate(
                () => [Page = GetPage(InitialUrl), Acc = {}],
                each [Page][Rows] <> null and not Table.IsEmpty([Page][Rows]),
                each [
                    Page = if [Page][Next] <> null then GetPage([Page][Next]) else [Rows = null, Next = null],
                    Acc = List.Combine({[Acc], {[Page][Rows]}})
                ],
                each [Page][Rows]
            ),
            
            // Combine all pages
            Combined = if List.Count(Loop) > 0 then Table.Combine(Loop) else #table({}, {}),
            
            // Expand record columns if data exists
            Expanded = if Table.IsEmpty(Combined) then 
                Combined 
            else 
                Table.ExpandRecordColumn(
                    Combined, 
                    "Column1", 
                    Record.FieldNames(Combined{0}[Column1])
                )
        in
            Expanded,
    
    // Test connection function
    TestConnection = () =>
        let
            TestEndpoint = "/data/Devices?$top=1",
            TestResult = GetPaged(TestEndpoint),
            IsConnected = not Table.IsEmpty(TestResult)
        in
            IsConnected,
    
    // Connection metadata
    ConnectionInfo = [
        BaseUrl = BaseUrl,
        ApiVersion = "v1.0",
        AuthType = "Organizational Account",
        RequiredPermissions = {
            "DeviceManagementConfiguration.Read.All",
            "DeviceManagementManagedDevices.Read.All", 
            "DeviceManagementApps.Read.All"
        }
    ]
in
    [
        BaseUrl = BaseUrl,
        Headers = JsonHeaders,
        GetPaged = GetPaged,
        TestConnection = TestConnection,
        ConnectionInfo = ConnectionInfo
    ]