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

/** Attaches to any entity (lead, customer, company) via entity_type/entity_id — see docs/ARCHITECTURE.md's note on polymorphic tables. */
final class NoteController 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:5000',
        ]);

        $id = (new NoteModel())->create($data['entity_type'], (int) $data['entity_id'], $data['body'], $this->currentUserId());

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

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

    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 NoteModel())->forEntity($params['entityType'], (int) $params['entityId']);

        return AjaxResponse::success($rows);
    }

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

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