/**
 * Flow action "Generate Worker ID Wallet Link".
 * Calls the Worker ID Wallet Service (POST /api/v1/passes/link) and returns a shareable URL to a page
 * with Add to Apple Wallet / Add to Google Wallet buttons. The link expires after 30 days.
 *
 * Setup: a Named Credential called "WorkerIdWallet" that points at the service and sends the
 * x-api-key header (see the Apex and Flow guide). Branding is set once in BRANDING below.
 */
public with sharing class WorkerIdWalletLink {
    // Static branding for every card your org issues. Edit to match your company; colours are #rrggbb.
    @TestVisible
    private static final Map<String, Object> BRANDING = new Map<String, Object>{
        'primaryColor' => '#3e344a',   // card background
        'secondaryColor' => '#00ca72', // labels (Apple only)
        'tertiaryColor' => '#ffffff',  // values (Apple only)
        'title' => '3B4SF'             // text next to the logo, max 30 chars
        // 'logoSvg' => '<svg ...>...</svg>' // optional custom logo, keep it small
    };
    private static final String ENDPOINT = 'callout:WorkerIdWallet/api/v1/passes/link';

    public class Request {
        @InvocableVariable(label='First Name' required=true)
        public String firstName;
        @InvocableVariable(label='Middle Name')
        public String middleName;
        @InvocableVariable(label='Last Name' required=true)
        public String lastName;
        @InvocableVariable(label='Company' required=true)
        public String company;
        @InvocableVariable(label='Date of Birth' required=true)
        public Date dob;
        @InvocableVariable(label='Employee ID' required=true)
        public String employeeId;
        @InvocableVariable(label='QR Data' description='Encoded in the QR code. Defaults to Employee ID.')
        public String qrData;
        @InvocableVariable(label='Photo URL' description='Public https URL of the worker photo, from an allowed host.')
        public String photoUrl;
        @InvocableVariable(label='Target Wallet' description='apple, google or both (default both).')
        public String targetWallet;

        @InvocableVariable(label='Front Detail Labels' description='Up to 3. Matched by position with Front Detail Values.')
        public List<String> frontLabels;
        @InvocableVariable(label='Front Detail Values' description='Rows with a blank value are skipped.')
        public List<String> frontValues;
        @InvocableVariable(label='Back Detail Labels' description='Up to 10. Matched by position with Back Detail Values.')
        public List<String> backLabels;
        @InvocableVariable(label='Back Detail Values' description='Rows with a blank value are skipped.')
        public List<String> backValues;
        @InvocableVariable(label='Back Notice' description='Text at the bottom of the back of the card.')
        public String notice;
    }

    public class Result {
        @InvocableVariable(label='Success')
        public Boolean isSuccess = false;
        @InvocableVariable(label='Link URL')
        public String url;
        @InvocableVariable(label='Expires At')
        public Datetime expiresAt;
        @InvocableVariable(label='Error Code')
        public String errorCode;
        @InvocableVariable(label='Error Message')
        public String errorMessage;
    }

    // One callout per request, so a single transaction handles at most 100 (Salesforce callout limit).
    @InvocableMethod(
        label='Generate Worker ID Wallet Link'
        description='Creates a shareable Apple/Google Wallet link for a Digital Worker ID.'
        category='Worker ID'
        callout=true
    )
    public static List<Result> generate(List<Request> requests) {
        List<Result> results = new List<Result>();
        for (Request r : requests) {
            results.add(generateOne(r));
        }
        return results;
    }

    private static Result generateOne(Request r) {
        Result res = new Result();
        try {
            HttpRequest req = new HttpRequest();
            req.setEndpoint(ENDPOINT);
            req.setMethod('POST');
            req.setHeader('Content-Type', 'application/json');
            req.setTimeout(30000);
            req.setBody(JSON.serialize(body(r), true));
            HttpResponse resp = new Http().send(req);

            Integer status = resp.getStatusCode();
            Map<String, Object> json = parse(resp.getBody());
            if (status == 201 && json?.get('url') != null) {
                res.isSuccess = true;
                res.url = (String) json.get('url');
                res.expiresAt = (Datetime) JSON.deserialize('"' + json.get('expiresAt') + '"', Datetime.class);
                return res;
            }
            // Service errors look like { "error": { "code", "message", "details"? } }.
            Map<String, Object> err = json?.get('error') instanceof Map<String, Object>
                ? (Map<String, Object>) json.get('error')
                : new Map<String, Object>();
            res.errorCode = err.containsKey('code') ? (String) err.get('code') : 'HTTP_' + status;
            res.errorMessage = err.containsKey('message') ? (String) err.get('message') : 'Unexpected response (HTTP ' + status + ')';
            if (err.get('details') != null) {
                res.errorMessage += ': ' + JSON.serialize(err.get('details'));
            }
        } catch (Exception e) {
            res.errorCode = e instanceof InputException ? 'VALIDATION_ERROR' : 'CALLOUT_FAILED';
            res.errorMessage = e.getMessage();
        }
        return res;
    }

    @TestVisible
    private static Map<String, Object> body(Request r) {
        return new Map<String, Object>{
            'firstName' => r.firstName,
            'middleName' => r.middleName,
            'lastName' => r.lastName,
            'company' => r.company,
            'dob' => r.dob == null ? null : String.valueOf(r.dob), // yyyy-MM-dd
            'employeeId' => r.employeeId,
            'qrData' => r.qrData,
            'photoUrl' => r.photoUrl,
            'targetWallet' => String.isBlank(r.targetWallet) ? null : r.targetWallet.trim().toLowerCase(),
            'branding' => BRANDING,
            'additionalDetails' => new Map<String, Object>{
                'front' => rows(r.frontLabels, r.frontValues, 'Front'),
                'back' => rows(r.backLabels, r.backValues, 'Back'),
                'notice' => r.notice
            }
        };
    }

    // Zips parallel label/value lists into [{ label, value }], dropping rows with no value.
    private static List<Map<String, String>> rows(List<String> labels, List<String> values, String side) {
        List<Map<String, String>> out = new List<Map<String, String>>();
        Integer n = labels == null ? 0 : labels.size();
        if (n != (values == null ? 0 : values.size())) {
            throw new InputException(side + ' Detail Labels and Values must have the same number of items');
        }
        for (Integer i = 0; i < n; i++) {
            if (String.isNotBlank(values[i])) {
                out.add(new Map<String, String>{ 'label' => labels[i], 'value' => values[i] });
            }
        }
        return out;
    }

    private static Map<String, Object> parse(String s) {
        try {
            Object o = JSON.deserializeUntyped(s);
            return o instanceof Map<String, Object> ? (Map<String, Object>) o : null;
        } catch (Exception e) {
            return null; // non-JSON body (e.g. a proxy error page); caller reports the HTTP status
        }
    }

    public class InputException extends Exception {}
}
