/**
 * @NApiVersion 2.x
 * @NScriptType UserEventScript
 */

define(['N/email', 'N/runtime', 'N/record', 'N/search'], function(email, runtime, record, search) {

    function beforeSendEmail(context) {
        var transaction = context.record;
        var user = runtime.getCurrentUser();
        var groupId = 123; // Replace with your group internal ID
        var fromEmail = 'Customer.Service@ahs-ltd.co.uk';

        // Only run for Purchase Orders
        if (transaction.type !== record.Type.PURCHASE_ORDER) {
            return;
        }

        // Check if user is in the group
        var isInGroup = false;
        var groupSearch = search.create({
            type: search.Type.ENTITY_GROUP,
            filters: [
                ['internalid', 'anyof', groupId],
                'AND',
                ['groupmember.internalid', 'anyof', user.id]
            ],
            columns: ['internalid']
        });
        var results = groupSearch.run().getRange({ start: 0, end: 1 });
        if (results && results.length > 0) {
            isInGroup = true;
        }

        // If user is in group, override the from address
        if (isInGroup) {
            context.sender = fromEmail;
        }
    }

    return {
        beforeSendEmail: beforeSendEmail
    };
});