What a mess this is...
The insurance company covers the present value of the car at the time it was totaled, as determined by...the insurance company. Most cars depreciate significantly during the first year of ownership. So figure your 3 month old 40k Tesla is now worth in the ballpark of 35k for insurance purposes.
The leasing company will demand from you the current
buyout value of the lease. This is equal to the purchase price of the car plus interest to that point minus lease payments (including down payment) already made. This is equivalent to the residual value of the car at the end of lease, plus unpaid lease minus remaining interest.
In short, none of us can tell you what the buyout number will be. However, it will likely be closer to the hypothetical 40k than the current value of 35k. So the 35k insurance settlement would be split like this: 27.5k to the lienholder (40k purchase + nominal amount of interest over 3 months - 12k down - 500 in monthly payments), 7.5k to you.
In this case you've lost the part of your down payment equal to the depreciation of the car over 3 months as determined by your lease contract buyout and insurance settlement. GAP insurance would have done nothing for you here since you actually had equity in the lease contract because of the down payment. Also, you're going to lose any sales tax that you paid when you purchased the car, which I believe would have been based on your 12k down payment. So this would further reduce the amount of money you'd get back from the insurance company through a proportionately higher buyout number.
I don't know what CA law is like, but in many states if you were not at fault you may have additional options to make yourself whole. You'd need to talk to a lawyer about your specific case though.
Borrowed a little from here, it's a good discussion:
Suppose leased car is totalled: what are financial implications?
Best of luck!
*edit*
Looks like in CA the insurer has to include taxes and fees for a comparable vehicle in their settlement. Uncertain how this would apply in a lease situation with an unusually high down payment...
Total loss settlements: States requiring insurers to pay your sales tax after a totaled car