<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\TaskProjectTasks\StoreTaskProjectTaskRequest;
use App\Http\Requests\TaskProjectTasks\UpdateTaskProjectTaskRequest;
use App\Models\TaskProject;
use App\Models\TaskProjectTask;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class TaskProjectTaskController extends Controller
{
    public function index(): JsonResponse
    {
        $userId = Auth::id();
        $items = TaskProjectTask::query()
            ->where('user_id', $userId)
            ->orderByDesc('due_date')
            ->orderByDesc('id')
            ->get();

        return $this->success($items, 'Task project tasks list');
    }

    public function store(StoreTaskProjectTaskRequest $request): JsonResponse
    {
        $userId = Auth::id();
        $validated = $request->validated();

        $projectId = (int) ($validated['task_project_id'] ?? 0);
        $ownsProject = TaskProject::query()->where('id', $projectId)->where('user_id', $userId)->exists();
        if (!$ownsProject) {
            return $this->error('Invalid task_project_id', 422);
        }

        $item = TaskProjectTask::create(array_merge($validated, ['user_id' => $userId]));

        return $this->success($item, 'Task project task created', 201);
    }

    public function show(TaskProjectTask $taskProjectTask): JsonResponse
    {
        $userId = Auth::id();
        if ((int) $taskProjectTask->user_id !== (int) $userId) {
            return $this->error('Not found', 404);
        }

        return $this->success($taskProjectTask, 'Task project task details');
    }

    public function update(UpdateTaskProjectTaskRequest $request, TaskProjectTask $taskProjectTask): JsonResponse
    {
        $userId = Auth::id();
        if ((int) $taskProjectTask->user_id !== (int) $userId) {
            return $this->error('Not found', 404);
        }

        $validated = $request->validated();

        if (array_key_exists('task_project_id', $validated)) {
            $projectId = (int) ($validated['task_project_id'] ?? 0);
            $ownsProject = TaskProject::query()->where('id', $projectId)->where('user_id', $userId)->exists();
            if (!$ownsProject) {
                return $this->error('Invalid task_project_id', 422);
            }
        }

        $taskProjectTask->update($validated);

        return $this->success($taskProjectTask, 'Task project task updated');
    }

    public function destroy(TaskProjectTask $taskProjectTask): JsonResponse
    {
        $userId = Auth::id();
        if ((int) $taskProjectTask->user_id !== (int) $userId) {
            return $this->error('Not found', 404);
        }

        $taskProjectTask->delete();

        return $this->success(null, 'Task project task deleted');
    }
}
