<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\Request;
use App\Core\Response;
use App\Helpers\AjaxResponse;
use App\Models\TaskModel;
use App\Services\ActivityLogger;

final class TaskController extends BaseController
{
    public function store(Request $request): Response
    {
        $data = $this->validateOrFail($request, [
            'lead_id' => 'required|integer|exists:leads,id',
            'title' => 'required|string|max:191',
            'due_at' => 'nullable|date',
            'assigned_to' => 'nullable|integer|exists:users,id',
        ]);
        $data['is_completed'] = 0;

        $model = new TaskModel();
        $id = $model->insert($data);

        ActivityLogger::record('lead', (int) $data['lead_id'], 'task_created', "Task created: \"{$data['title']}\"");

        return AjaxResponse::created(null, 'Task added.');
    }

    public function toggle(Request $request, array $params): Response
    {
        $id = (int) $params['id'];
        $completed = (bool) $request->input('is_completed', true);

        (new TaskModel())->toggleComplete($id, $completed);

        return AjaxResponse::success(null, $completed ? 'Task marked complete.' : 'Task reopened.');
    }

    public function destroy(Request $request, array $params): Response
    {
        (new TaskModel())->delete((int) $params['id']);

        return AjaxResponse::success(null, 'Task removed.');
    }

    public function myTasks(Request $request): Response
    {
        $rows = (new TaskModel())->upcomingFor($this->currentUserId());

        return AjaxResponse::success($rows);
    }
}
