public class RiabuOrderSync {

    public static String syncOrders(String riabuCustomerId) {

        System.debug('START — RiabuOrderSync for CustomerId: ' + riabuCustomerId);

        // Load Integration Config
        RIABU_Integration__mdt config = [
            SELECT Access_Token__c, RIABU_Fetch_Orders_Endpoint__c
            FROM RIABU_Integration__mdt
            WHERE DeveloperName = 'Riabu_Record'
            LIMIT 1
        ];

        if (config == null || config.RIABU_Fetch_Orders_Endpoint__c == null) {
            return 'Orders Endpoint missing in Metadata';
        }

        // Ensure correct format with trailing slash
        String baseEndpoint = config.RIABU_Fetch_Orders_Endpoint__c;
        if (!baseEndpoint.endsWith('/')) {
            baseEndpoint += '/';
        }

        String endpoint = baseEndpoint + riabuCustomerId + '?per-page=99999&page=1';
        System.debug('Final API Endpoint: ' + endpoint);

        HttpRequest req = new HttpRequest();
        req.setEndpoint(endpoint);
        req.setMethod('GET');
        req.setHeader('Authorization', 'Bearer ' + config.Access_Token__c);

        Http http = new Http();
        HttpResponse res = http.send(req);

        System.debug('Response Code: ' + res.getStatusCode());
        System.debug('Response Body: ' + res.getBody());

        if (res.getStatusCode() != 200) {
            return 'Riabu Order Fetch Error: ' + res.getStatus();
        }

        Map<String, Object> root =
            (Map<String, Object>) JSON.deserializeUntyped(res.getBody());

        if (root == null || root.get('data') == null) {
            return 'Invalid or Empty Riabu Response';
        }

        Map<String, Object> data = (Map<String, Object>) root.get('data');
        List<Object> items = (List<Object>) data.get('items');

        if (items == null || items.isEmpty()) {
            return 'No Orders Found in Riabu';
        }

        System.debug('Total Orders Returned: ' + items.size());

        Account acc;
        try {
            acc = [
                SELECT Id FROM Account
                WHERE RIABU_Customer_ID__c = :riabuCustomerId
                LIMIT 1
            ];
        } catch (Exception e) {
            return 'No Matching Salesforce Account Found';
        }

        List<Opportunity> oppsToUpsert = new List<Opportunity>();

        for (Object o : items) {
            Map<String, Object> order = (Map<String, Object>) o;

            String riabuOrderId = String.valueOf(order.get('id'));

            Opportunity opp = new Opportunity();
            opp.Riabu_Order_Id__c = riabuOrderId;
            opp.AccountId = acc.Id;

            // Name
            opp.Name = String.isNotBlank((String)order.get('opportunity'))
                ? (String) order.get('opportunity')
                : 'Order ' + riabuOrderId;

            // Amount
            if (order.get('total_invoice_amount') != null) {
                opp.Amount = Decimal.valueOf(String.valueOf(order.get('total_invoice_amount')));
            }

            // Close Date
            try {
                if (order.get('invoice_due_date') != null) {
                    opp.CloseDate = Date.valueOf(
                        String.valueOf(order.get('invoice_due_date'))
                    );
                } else {
                    opp.CloseDate = Date.today().addDays(7);
                }
            } catch (Exception ex) {
                opp.CloseDate = Date.today().addDays(7);
            }

            opp.StageName = 'Prospecting';

            oppsToUpsert.add(opp);
        }

        if (!oppsToUpsert.isEmpty()) {
            upsert oppsToUpsert Riabu_Order_Id__c;
            return oppsToUpsert.size() + ' Orders Synced (Upserted)';
        }

        return 'No New Orders to Sync';
    }
}