Let's assume simple differential equation:
$$\frac{d^2}{dx^2}y=2 \quad y(\pm1)=0$$ the solution for the equation is: $$y=x^2-1$$ and the Fourier transform for the $y(x)$ in the solution interval $[-1,1]$: $$y(x)=\frac{-2}{3}+\sum_{n=1}^{\infty}{\frac{4(-1)^n\cos(n\pi x)}{n^2\pi ^2}}$$ by substituting the Fourier series inside the original equation: $$\frac{d^2}{dx^2}y(x)=\sum_{n=1}^{\infty}{4(-1)^{n+1}\cos(n\pi x)\neq2}$$
But we can solve the equation by assuming Fourier series that fulfill Boundary conditions $$y(x)=\sum_{n=0}^{\infty}A_n \cos(\frac{2n+1}{2}\pi x)$$ The constant term can be transformed to $$2=\sum_{n=0}^{\infty}\frac{8(-1)^n}{(2n+1)\pi}\cos(\frac{2n+1}{2}\pi x)$$ $$\frac{d^2}{dx^2}y(x)=\sum_{n=0}^{\infty}A_n\frac{-(2n+1)^2\pi^2}{4} \cos(\frac{2n+1}{2}\pi x)$$ $$A_n\frac{-(2n+1)^2\pi^2}{4}=\frac{8(-1)^n}{(2n+1)\pi}$$ $$A_n=\frac{32(-1)^{n+1}}{(2n+1)^3\pi^3}$$ which can be proven to satisfy the required solution: $$y(x)=\sum_{n=0}^{\infty}A_n \cos(\frac{2n+1}{2}\pi x)=x^2-1$$ What I misunderstand?
Why the first attempt is wrong?
But it actually uses orthogonal basis in the solution interval.
Your first series expansion $$ f_1(x) = -\frac{2}{3} + \sum_{n=0}^\infty \frac{4(-1)^n}{n^2\pi^2}\cos(n\pi x) $$ is the series expansion of the periodic extension of $1-x^2$, which means it is the expansion of a function whose derivative is discontinuous at $\pm 1$, $\pm 3$, etc. This is why when you try to differentiate the series twice term by term, you end up with a series that is not convergent (i.e., differentiating a Fourier series of a discontinuous function is a no-no).
By construction (you found it by integrating twice) your second solution $$ f_2(x) = \sum_{n=0}^\infty \frac{32(-1)^{n+1}}{(2n+1)^3\pi^3}\cos\left(\frac{2n+1}{2}\pi x\right) $$ is the Fourier series of a function whose derivative is continuous, and whose second derivative is piecewise smooth, so it can be differentiated twice term by term. It is actually the periodic extension of $$ f(x) = \begin{cases}x^2 -1 & -1 < x < 1 \\ 1 - (x-2)^2 & 1 < x < 3 \end{cases}. $$