For indispensable reporting on the coronavirus crisis, the election, and more, subscribe to the Mother Jones Daily newsletter.

This story was originally published by ProPublica, a nonprofit newsroom that investigates abuses of power. Sign up for ProPublica’s The Big Story newsletter to receive stories like this one in your inbox as soon as they are published.

In March 2008, as Facebook was speeding toward 100 million users and emerging as the next big tech company, it announced an important hire. Sheryl Sandberg was leaving Google to become Facebook’s chief operating officer. CEO Mark Zuckerberg, then 23 years old, told The New York Times that Sandberg would take the young company “to the next level.”

Based on her time at Google, Sandberg soon decided that one area where Facebook was behind its peers was in its tax dodging. “My experience is that by not having a European center and running everything through the US, it is very costly in terms of taxes,” she wrote other executives in an April 2008 email, which hasn’t been previously reported. Facebook’s head of tax agreed, replying that the company needed to find “a low taxed jurisdiction to park profits.”

Later that year, Facebook named Dublin as its international headquarters, just as Google had done when Sandberg was there. And just like Google, Facebook concocted an intra-company deal to “park profits” in Ireland, where it would pay a tax rate near zero.

Like its Big Tech peers, Facebook wasn’t much afraid of the IRS. But, as it happened, the same year that Facebook started moving profits to Ireland, the IRS launched a team to crack down on deals like that. The effort started aggressively. As we recently reported, the IRS threw everything it had at Microsoft in the largest audit in the agency’s history.

But shortly after the IRS showed this new ambition, Republicans in Congress, after taking the House in 2010, began forcing cuts to the IRS’ budget. Over the years, as Facebook grew into one of the world’s largest companies, with 2 billion users, the IRS was shrinking. By the time the IRS finally took on Facebook over its Irish deal a few years later, the agency was in over its head.

ProPublica pieced together the story of the Facebook audit from court documents filed by the two sides in their yearslong battle. (Both the IRS and the company declined to comment.) The picture revealed by the documents provides a crucial window into the IRS’ struggles to check large corporations’ tax schemes.

At one point in the audit, the exam stalled for months because there was no money to hire an expert. Agents tried for five years to pick apart the deal’s complexities and were still scrambling when the statute of limitations expired in July 2016. Like a student forced, when the bell rings, to turn in a test with unanswered questions, the IRS sent Facebook the results of its incomplete audit. Based on the work it had done, the IRS thought Facebook had massively mispriced its Irish deal and should have paid billions more in taxes.

Today the fight continues before the U.S. Tax Court, and the conflict is about to reach a climax: A trial is scheduled for February, and the IRS is trying to convince a judge that it has a firm basis for its conclusions. For its part, Facebook has defended its actions in court filings, calling the IRS’ conclusions “arbitrary, capricious, or unreasonable.”

If the IRS prevails in court, it could cost Facebook up to $9 billion more in taxes, based on estimates in the company’s securities filings. It would be a notable defeat for a company that, when it comes to risky tax avoidance, has been more aggressive “than almost any other U.S. corporation,” said Matt Gardner, a senior fellow at the nonprofit Institute on Taxation and Economic Policy. According to Facebook’s public filings, from 2010 through 2017 (when the U.S. corporate tax rate was 35%), the company paid a total of $3.9 billion in taxes on $50 billion of pre-tax income, a rate of about 8%.

Still, the IRS hasn’t won a clear victory in a major profit-shifting case in court for decades, said Reuven Avi-Yonah, a professor at the University of Michigan Law School and an expert on international tax. The agency, he said, has simply been “overmatched.” Given how things have gone so far in its conflict with the IRS, Facebook has good reason to be confident about the coming trial.

From the beginning in 2008, Facebook laid the foundations of its big profit shift with care, according to internal company emails disclosed by the IRS in court filings. The first step was to establish a company office in a low-tax country. Given Sandberg’s experience helping Google choose Dublin and set up its office there, Ireland was the first option. Then the question was what and who to put there. The key was having just enough of a presence in Dublin “to justify the tax benefits,” Sandberg wrote in an email at the time.

A Facebook finance executive explained that, to get “the tax advantages,” Facebook needed to transfer its intellectual property to the Dublin office. There needed to be servers there with “the key source code and user data” on them in order to “build the case” for the transfer. When a Facebook executive grumbled, “Ireland is not a first or second choice for a significant data center presence,” because it was easier to hire people in London, the tax exec responded that the Dublin center wouldn’t need to be particularly large.

In other words, it didn’t really matter how many people worked in the Dublin office. Yet, in October 2008 when Facebook publicly announced its choice of what it grandly called its “international headquarters,” Sandberg was quoted in a press release singing the praises of the Irish workforce. “After exploring various locations throughout the region, we decided Ireland was the best place,” she said. “The talent pool in Dublin is world-class and recruiting local talent will help us better understand the needs of local users.”

In a private email to an old Google colleague the previous day, however, she’d been frank. “Same decision process Google went through a long time ago,” she wrote: “tax breaks to put international revenue through. Our operations there will be very small—maybe 10 people by end of this year and 30-50 by end of next year.”

The main pieces now in place, Facebook started constructing its deal to move profits to Ireland. It set up an Irish company that declared itself to have management in the Cayman Islands. This was a trick to avoid paying even Ireland’s low 12.5% tax rate on the profits: The company would instead pay close to nothing. Now it just needed some profits. Essentially, Facebook would license its software platform to its Irish subsidiary, and this would in turn entitle the Irish subsidiary to a portion of Facebook’s profits.

IRS rules allow such intra-company deals, but the companies are supposed to arrive at a fair, “arm’s-length” price. How much the Irish company would pay for the license and what portion of Facebook’s profits the Dublin office would get—these are not numbers that companies can just make up. It doesn’t matter that the transaction was highly artificial, without any clear real-world models. The price is supposed to have some objective basis.

To conjure the prices Facebook should pay in this deal with itself, Facebook hired the giant accounting firm Ernst & Young. The firm’s experts and economists worked for years on the project. In 2011, a year after the deal had officially closed, E&Y’s team was still crunching figures and generating reports.

In September 2011, an E&Y economist emailed 600 pages of analysis to Ted Price, Facebook’s head of tax, and offered to send him three printed copies: two for his team, and one for the IRS, should the agency ever come calling. Price said that he’d take three, but they’d all be for his team. “I doubt the IRS ever even audits us on this,” he wrote. The E&Y economist replied, “knock on wood.” (In a court filing, Facebook said Price’s comment was “sarcastic.”)

The IRS began its audit, as it happened, soon afterward. But it wasn’t until 2015 that a team of agents presented preliminary findings to Facebook. The IRS thought E&Y’s estimates were off by billions of dollars. (E&Y declined to comment.)

A month later, Facebook responded with a presentation of its own that blasted the IRS’ analysis. The agency “had made significant and arbitrary errors,” Facebook later claimed in legal filings.

The IRS decided to regroup. The agency needed help, the team working the case decided, and for that, it would hire outside experts.

But there was a problem. In late 2014, Republicans in Congress had forced through a sudden $346 million cut to the IRS’ budget, and money was tight. Although billions of dollars were at stake in the Facebook audit, the IRS had no funds to hire an expert. The audit team had to wait for three months, until the new fiscal year began in October 2015, to even begin looking. Then, because of a lengthy contracting process, it took six more months for the $800,000 contract to go through. The expert, an economist who specializes in analyzing these intra-company deals, finally went to work in March 2016.

Meanwhile, the IRS was struggling to get all the documents it needed from Facebook. In January 2016, the exam team had sent off a broad request for documents about the Irish deal.

Two months later, Facebook turned over three emails in response. The company told the IRS it had “narrowly construed” the request, one of the agents on the case, Nina Wu Stone, later declared in court, and “the IRS would have to start over with issuance of a new set of [requests] if the IRS wanted a more comprehensive response.”

At the same time, the IRS feared being buried in paper. In response to another request, Facebook told the IRS the company’s systems couldn’t efficiently sort for responsive documents, and as a result, Facebook was going to turn over so much that it would “perhaps overwhelm the IRS,” as the agency put it in a court filing.

Through all of this, the clock was ticking. The IRS has three years to assess additional tax on a return, but corporate taxpayers often voluntarily extend the statute of limitations. In this case, Facebook had done so five times. Companies do this because they are hoping to avoid having to go to court.

But as the IRS began asking for more time to hire experts, Facebook decided it didn’t like where the audit was headed. The company played hardball. It offered to extend the statute again, but on one condition. The IRS had to commit that Facebook would be able to take its case to the IRS Office of Appeals.

The Office of Appeals offers taxpayers the prospect of a quiet settlement of a tax dispute, and as ProPublica reported in the story about the audit of Microsoft, large corporations often are able to obtain steep reductions in what they owe. But the IRS does have the power to block appeals. The agency rarely employs that power, but it had recently done so against other big taxpayers like Coca-Cola and Amazon. Facebook wanted to make sure that didn’t happen.

The IRS refused, and the clock continued to tick. By May 2016, with just two months left, the IRS managed to get its second expert working on the case. Nancy Bronson, an IRS supervisor, asked Facebook to reconsider an extension. That’s when Price, the Facebook executive, offered another exchange.

The IRS has a powerful tool to compel documents from large corporations that the agency thinks are dragging their feet. It’s called a “designated summons,” and it stops the clock until the taxpayer turns over all the requested documents. This can buy the IRS valuable time, but it angers corporations who must now endure added time to the audit.

Price told Bronson that Facebook would give the IRS six more months if it agreed not to use a designated summons. Again, Bronson declined. “I explained my reservations with giving up that right given the difficulties in obtaining information in a timely manner and the short period of the proposed statute extension,” she declared in a court filing.

Despite the apparent utility of designated summonses, the IRS has used them only three times since the mid-’90s. The most recent instance, against Microsoft in 2014, provoked a powerful response, and Microsoft and its corporate allies launched a lobbying campaign on Capitol Hill. Soon, lawmakers were introducing bills seeking to curtail the IRS’ use of designated summonses and other tools.

Against this added pressure, the IRS decided to take the middle path. The agency didn’t relinquish the ability to use the designated summons, but it didn’t take the aggressive step of actually using it, either. Instead, the IRS issued a conventional summons and then sued in federal district court to enforce it. This forced Facebook to turn over documents, but the clock continued to run and it would take months for Facebook to comply.

The IRS’ decision meant that it had to finish the audit without the benefit of documents that it characterized in court filings as essential to understanding Facebook’s Ireland deal. So, that’s what it did. Shortly before the statute expired, the IRS sent Facebook an official notice closing the audit. “The examination team had not completed its fact-gathering efforts when the notice was issued,” Bronson said.

The IRS concluded, based on its incomplete analysis, that Facebook’s Irish subsidiary had underpaid for Facebook’s software platform by $7 billion: The subsidiary had paid $7 billion when it should’ve paid $14 billion. If the IRS’ view prevailed, less profit would flow to Ireland and thus more income would be taxable in the U.S. As expected, Facebook soon filed a challenge in U.S. Tax Court.

The IRS said its findings weren’t absolutely final, because it could modify them in court as it acquired more evidence. But agency veterans say such changes are unusual and make the agency’s already difficult task—fighting a complex litigation battle against a better-resourced foe—even harder.

“I don’t think I’ve ever seen a case where the IRS increased an assessment after it came out of exam,” said Ken Wood, a former attorney with the IRS who worked on large corporate audits. Making any sort of change is “dangerous,” he said, because it can undermine the IRS’ argument that its findings are firmly supported.

Last October, in a legal filing, the IRS disclosed that, having had time to review the millions of pages of documents that Facebook had turned over since 2016, it now thought Facebook’s Irish company should have paid $20 billion in the original transaction. However, the agency was apparently wary of shaking up its case by officially modifying its earlier findings. Confusingly, the IRS said it would argue at trial that its earlier estimate was too low, while simultaneously preserving that low estimate as the basis of the trial. The IRS wasn’t definitely saying Facebook should pay more; It was suggesting to the judge that it should.

A couple months later, just before Christmas, the IRS reversed course. It filed a motion officially changing its earlier findings and made the $20 billion valuation its one and only position at trial.

It’s unclear just how much tax Facebook’s Irish deal has saved the company, because the company has also made other moves to reduce taxes. Since Facebook refuses to divulge details, back of the envelope calculations based on other company disclosures provide the best guess. On that basis, ProPublica estimates that Facebook shifted at least $19 billion in profits offshore.

If the company’s big tax dodge were upended, Facebook could be forced to pay up to $9 billion more in taxes, the company recently said, an increase from its earlier estimates of up to $5 billion before the IRS changed its demand. But despite the increased exposure, Facebook’s chances in Tax Court are good. A win would be just another windfall for a company that’s clearly reached “the next level.”

Kirsten Berg contributed to this story.