<?php

namespace App\Http\Controllers;

use App\Models\Entry;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class EntryController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return Entry::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',
            'content' => 'required|string',
        ]);

        $validated['slug'] = $this->generateUniqueSlug($validated['title']);

        return Entry::create($validated);
    }

    private function generateUniqueSlug(string $title): string
    {
        do {
            $slug = Str::slug($title) . '-' . Str::random(8);
        } while (Entry::where('slug', $slug)->exists());

        return $slug;
    }

    /**
     * Display the specified resource.
     */
    public function show(Entry $entry)
    {
        $this->authorize('view', $entry);

        return $entry;
    }

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

        $entry->update($validated);

        return $entry;
    }

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

        return response()->noContent();
    }

    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return Auth::check();
    }
}
