<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Note;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class NoteController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = $request->user()->notes();

        if ($request->has('search')) {
            $query->search($request->search);
        }

        $notes = $query->orderByDesc('pinned')
            ->orderByDesc('updated_at')
            ->get();

        return response()->json([
            'success' => true,
            'data' => $notes,
        ]);
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'nullable|string',
            'color' => 'in:yellow,blue,green,pink,purple,gray',
            'pinned' => 'boolean',
        ]);

        $note = $request->user()->notes()->create($validated);

        return response()->json([
            'success' => true,
            'data' => $note,
            'message' => 'Notiz erstellt.',
        ], 201);
    }

    public function update(Request $request, string $id): JsonResponse
    {
        $note = $request->user()->notes()->findOrFail($id);

        $validated = $request->validate([
            'title' => 'sometimes|string|max:255',
            'content' => 'nullable|string',
            'color' => 'in:yellow,blue,green,pink,purple,gray',
            'pinned' => 'boolean',
        ]);

        $note->update($validated);

        return response()->json([
            'success' => true,
            'data' => $note->fresh(),
            'message' => 'Notiz aktualisiert.',
        ]);
    }

    public function destroy(Request $request, string $id): JsonResponse
    {
        $note = $request->user()->notes()->findOrFail($id);
        $note->delete();

        return response()->json([
            'success' => true,
            'data' => null,
            'message' => 'Notiz gelöscht.',
        ]);
    }
}
