<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\BaseModel;

final class CommentModel extends BaseModel
{
    protected string $table = 'comments';
    protected array $fillable = ['entity_type', 'entity_id', 'parent_id', 'body'];
    protected bool $softDeletes = true;
    protected bool $auditStamps = false;

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

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

    /** Flat list, newest first — the view groups replies under their parent client-side by parent_id. */
    public function forEntity(string $entityType, int $entityId): array
    {
        $stmt = $this->db->prepare(
            "SELECT c.*, CONCAT(u.first_name, ' ', u.last_name) AS author_name
             FROM comments c
             LEFT JOIN users u ON u.id = c.created_by
             WHERE c.entity_type = :type AND c.entity_id = :id AND c.deleted_at IS NULL
             ORDER BY c.created_at ASC"
        );
        $stmt->execute(['type' => $entityType, 'id' => $entityId]);

        return $stmt->fetchAll();
    }
}
