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

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

    public function store(Request $request): Response
    {
        $data = $this->validateOrFail($request, [
            'entity_type' => 'required|in:lead,customer,company',
            'entity_id' => 'required|integer',
            'body' => 'required|string|max:2000',
            'parent_id' => 'nullable|integer|exists:comments,id',
        ]);

        $id = (new CommentModel())->create(
            $data['entity_type'],
            (int) $data['entity_id'],
            $data['body'],
            $this->currentUserId(),
            isset($data['parent_id']) ? (int) $data['parent_id'] : null
        );

        ActivityLogger::record($data['entity_type'], (int) $data['entity_id'], 'comment_added', 'Comment added');

        return AjaxResponse::created(['id' => $id], 'Comment posted.');
    }

    public function index(Request $request, array $params): Response
    {
        if (!in_array($params['entityType'], self::ALLOWED_ENTITY_TYPES, true)) {
            return AjaxResponse::error('Invalid entity type.', 422);
        }

        $rows = (new CommentModel())->forEntity($params['entityType'], (int) $params['entityId']);

        return AjaxResponse::success($rows);
    }

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

        return AjaxResponse::success(null, 'Comment deleted.');
    }
}
