<?php
declare(strict_types=1);

namespace App\Models;

use PDO;

class MediaFile extends BaseModel
{
    protected string $table = 'media_files';

    public function listForAdmin(array $filters = [], int $limit = 160): array
    {
        $limit = min(max($limit, 1), 300);
        $where = ['COALESCE(mf.is_active, 1) = 1'];
        $params = [];

        if (!empty($filters['context'])) {
            $where[] = 'mf.context = :context';
            $params['context'] = substr((string) $filters['context'], 0, 80);
        }

        if (!empty($filters['q'])) {
            $where[] = '(mf.file_name LIKE :q_name OR mf.file_path LIKE :q_path OR mf.context LIKE :q_context)';
            $like = '%' . trim((string) $filters['q']) . '%';
            $params['q_name'] = $like;
            $params['q_path'] = $like;
            $params['q_context'] = $like;
        }

        $sql = 'SELECT mf.*, u.username AS uploader_username
                FROM media_files mf
                LEFT JOIN users u ON u.id = mf.user_id
                WHERE ' . implode(' AND ', $where) . '
                ORDER BY mf.created_at DESC, mf.id DESC
                LIMIT :limit';

        $statement = $this->db()->prepare($sql);
        foreach ($params as $key => $value) {
            $statement->bindValue($key, $value);
        }
        $statement->bindValue('limit', $limit, PDO::PARAM_INT);
        $statement->execute();

        return $statement->fetchAll();
    }

    public function find(int $id): ?array
    {
        $statement = $this->db()->prepare('SELECT * FROM media_files WHERE id = :id LIMIT 1');
        $statement->execute(['id' => $id]);
        $row = $statement->fetch();

        return $row ?: null;
    }

    public function createFromUpload(array $data): int
    {
        $statement = $this->db()->prepare(
            'INSERT INTO media_files
                (user_id, file_path, file_name, mime_type, file_size, file_type, context, is_active, created_at)
             VALUES
                (:user_id, :file_path, :file_name, :mime_type, :file_size, :file_type, :context, 1, NOW())'
        );
        $statement->execute([
            'user_id' => $data['user_id'] ?? null,
            'file_path' => (string) $data['file_path'],
            'file_name' => substr((string) $data['file_name'], 0, 190),
            'mime_type' => substr((string) $data['mime_type'], 0, 120),
            'file_size' => (int) $data['file_size'],
            'file_type' => substr((string) ($data['file_type'] ?? 'image'), 0, 60),
            'context' => substr((string) ($data['context'] ?? 'general'), 0, 80),
        ]);

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

    public function deactivate(int $id): void
    {
        $statement = $this->db()->prepare('UPDATE media_files SET is_active = 0 WHERE id = :id');
        $statement->execute(['id' => $id]);
    }
}
