You answered your own question - you need to check all the conditions and then create the code based on the results. How you do this depends on how you’ve designed your system. LS is likely to be the best approach and you’ll probably use a combination of things like ‘if/then’, ‘case’, and probably some kind of document that holds increment numbers (so you know to go from 001 to 002).
There is code posted elseswhere on how to do incremental counters (hint - look in the FAQ of FAQs…)
I’d also recommend you just write out the process used to decide how you’ll create a new number, then write the code to match what you wrote out.