<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\BaseModel;

/** Backs both "Documents" and "Files" from the brief — one polymorphic attachment table, since duplicating it per-name would just be the same schema twice. */
final class AttachmentModel extends BaseModel
{
    protected string $table = 'attachments';
    protected array $fillable = ['entity_type', 'entity_id', 'disk_path', 'original_name', 'mime_type', 'size_bytes', 'checksum_sha256', 'uploaded_by'];
    protected bool $timestamps = false;
    protected bool $softDeletes = true;
    protected bool $auditStamps = false;

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

        return $stmt->fetchAll();
    }
}
