<?php

namespace App\Http\Controllers;

use App\Models\TextWidget;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TextWidgetController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return TextWidget::all();
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $user = Auth::user();

        if (! $user || $user->email !== config('app.admin_email')) {
            return response()->json(['message' => 'Forbidden'], 403);
        }

        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'content' => 'required|string',
        ]);

        return TextWidget::create($validated);
    }

    /**
     * Display the specified resource.
     */
    public function show(TextWidget $textWidget)
    {
        return $textWidget;
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, TextWidget $textWidget)
    {
        $validated = $request->validate([
            'title' => 'sometimes|required|string|max:255',
            'description' => 'sometimes|nullable|string',
            'content' => 'sometimes|required|string',
        ]);

        $textWidget->update($validated);

        return $textWidget;
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(TextWidget $textWidget)
    {
        $textWidget->delete();

        return response()->noContent();
    }
}
