<?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\TagModel;
use App\Services\ActivityLogger;

final class TagController extends BaseController
{
    private const ALLOWED_ENTITY_TYPES = ['lead', 'customer', 'company'];

    public function index(Request $request): Response
    {
        $rows = (new TagModel())->all();

        return AjaxResponse::success($rows);
    }

    public function attach(Request $request): Response
    {
        $entityType = (string) $request->input('entity_type');
        $entityId = (int) $request->input('entity_id');
        $tagName = trim((string) $request->input('tag_name', ''));

        if (!in_array($entityType, self::ALLOWED_ENTITY_TYPES, true) || $entityId <= 0 || $tagName === '') {
            return AjaxResponse::error('Invalid tag request.', 422);
        }

        $model = new TagModel();
        $tagId = $model->findOrCreateByName($tagName);
        $model->attach($tagId, $entityType, $entityId);

        ActivityLogger::record($entityType, $entityId, 'tag_added', "Tagged \"{$tagName}\"");

        return AjaxResponse::success($model->forEntity($entityType, $entityId), 'Tag added.');
    }

    public function detach(Request $request, array $params): Response
    {
        $entityType = (string) $request->input('entity_type');
        $entityId = (int) $request->input('entity_id');
        $tagId = (int) $params['tagId'];

        (new TagModel())->detach($tagId, $entityType, $entityId);

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