<?php

namespace App\Http\Controllers\Api;

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

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

        if ($request->status === 'all') {
            // Keine Filterung — alle Tasks zurückgeben
        } elseif ($request->has('status')) {
            $query->ofStatus($request->status);
        } else {
            $query->where('status', '!=', 'done');
        }

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

        $tasks = $query->orderByRaw("FIELD(priority, 'high', 'medium', 'low')")
            ->orderBy('due_at')
            ->get();

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

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'title'       => 'required|string|max:255',
            'description' => 'nullable|string',
            'priority'    => 'in:low,medium,high',
            'due_at'      => 'nullable|date',
            'reminder_at' => 'nullable|date',
        ]);

        if ($request->filled('reminder_at')) {
            $limitError = $this->checkReminderLimit($request->user());
            if ($limitError) return $limitError;
        }

        $validated['status']        = 'pending';
        $validated['reminder_sent'] = false;

        $task = $request->user()->tasks()->create($validated);

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

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

        $validated = $request->validate([
            'title'       => 'sometimes|string|max:255',
            'description' => 'nullable|string',
            'status'      => 'in:pending,in_progress,done',
            'priority'    => 'in:low,medium,high',
            'due_at'      => 'nullable|date',
            'reminder_at' => 'nullable|date',
        ]);

        if ($request->filled('reminder_at') && $request->reminder_at !== optional($task->reminder_at)->toDateTimeString()) {
            $limitError = $this->checkReminderLimit($request->user(), $task->id);
            if ($limitError) return $limitError;
        }

        if (isset($validated['status']) && $validated['status'] === 'done' && ! $task->isDone()) {
            $validated['completed_at'] = now();
        }

        if (array_key_exists('reminder_at', $validated)) {
            $validated['reminder_sent'] = false;
        }

        $task->update($validated);

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

    private function checkReminderLimit(\App\Models\User $user, ?string $excludeTaskId = null): ?\Illuminate\Http\JsonResponse
    {
        $isPro = $user->subscription?->plan?->plan_key !== 'free';
        if ($isPro) return null;

        $query = Task::where('user_id', $user->id)
            ->whereNotNull('reminder_at')
            ->where('reminder_at', '>', now())
            ->where('reminder_sent', false)
            ->where('status', '!=', 'done');

        if ($excludeTaskId) {
            $query->where('id', '!=', $excludeTaskId);
        }

        $count = $query->count();

        if ($count >= 3) {
            return response()->json([
                'success' => false,
                'message' => 'limit_reached',
                'data'    => ['limit' => 3, 'current' => $count],
            ], 422);
        }

        return null;
    }

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

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