<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\BaseModel;

final class NoteModel extends BaseModel
{
    protected string $table = 'notes';
    protected array $fillable = ['entity_type', 'entity_id', 'body'];
    protected bool $softDeletes = true;
    protected bool $auditStamps = false; // notes only have created_by, not updated_by — handled manually below

    public function create(string $entityType, int $entityId, string $body, int $userId): int
    {
        $stmt = $this->db->prepare(
            'INSERT INTO notes (entity_type, entity_id, body, created_by, created_at, updated_at)
             VALUES (:type, :id, :body, :user, NOW(), NOW())'
        );
        $stmt->execute(['type' => $entityType, 'id' => $entityId, 'body' => $body, 'user' => $userId]);

        return (int) $this->db->lastInsertId();
    }

    public function forEntity(string $entityType, int $entityId): array
    {
        $stmt = $this->db->prepare(
            "SELECT n.*, CONCAT(u.first_name, ' ', u.last_name) AS author_name
             FROM notes n
             LEFT JOIN users u ON u.id = n.created_by
             WHERE n.entity_type = :type AND n.entity_id = :id AND n.deleted_at IS NULL
             ORDER BY n.created_at DESC"
        );
        $stmt->execute(['type' => $entityType, 'id' => $entityId]);

        return $stmt->fetchAll();
    }
}
