<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\TaskTemplates\StoreTaskTemplateRequest;
use App\Http\Requests\TaskTemplates\UpdateTaskTemplateRequest;
use App\Models\TaskTemplate;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class TaskTemplateController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(): JsonResponse
    {
        $userId = Auth::id();
        $templates = TaskTemplate::query()
            ->where('user_id', $userId)
            ->latest()
            ->get();

        return $this->success($templates, 'Task templates list');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreTaskTemplateRequest $request): JsonResponse
    {
        $userId = Auth::id();
        $data = $request->validated();
        $data['user_id'] = $userId;
        $template = TaskTemplate::create($data);

        return $this->success($template, 'Task template created', 201);
    }

    /**
     * Display the specified resource.
     */
    public function show(TaskTemplate $taskTemplate): JsonResponse
    {
        $userId = Auth::id();
        if ((int) $taskTemplate->user_id !== (int) $userId) {
            return $this->error('Not found', null, 404);
        }
        return $this->success($taskTemplate, 'Task template details');
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateTaskTemplateRequest $request, TaskTemplate $taskTemplate): JsonResponse
    {
        $userId = Auth::id();
        if ((int) $taskTemplate->user_id !== (int) $userId) {
            return $this->error('Not found', null, 404);
        }
        $taskTemplate->update($request->validated());

        return $this->success($taskTemplate, 'Task template updated');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(TaskTemplate $taskTemplate): JsonResponse
    {
        $userId = Auth::id();
        if ((int) $taskTemplate->user_id !== (int) $userId) {
            return $this->error('Not found', null, 404);
        }
        $taskTemplate->delete();

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