<?php

declare(strict_types=1);

namespace ServerManager\Models;

use ServerManager\Core\Database;

class CommandHistory
{
    private Database $db;

    public function __construct()
    {
        $this->db = Database::getInstance();
    }

    public function log(int $serverId, int $userId, string $command, ?string $output, int $exitStatus): int
    {
        return $this->db->insert('command_history', [
            'server_id' => $serverId,
            'user_id' => $userId,
            'command' => $command,
            'output' => mb_substr($output ?? '', 0, 65535),
            'exit_status' => $exitStatus,
            'executed_at' => date('Y-m-d H:i:s'),
        ]);
    }

    public function getByServer(int $serverId, int $limit = 50): array
    {
        return $this->db->fetchAll(
            'SELECT ch.*, u.username 
             FROM command_history ch 
             LEFT JOIN users u ON ch.user_id = u.id 
             WHERE ch.server_id = ? AND ch.status = \'active\'
             ORDER BY ch.executed_at DESC 
             LIMIT ?',
            [$serverId, $limit]
        );
    }

    public function getRecent(int $limit = 10): array
    {
        return $this->db->fetchAll(
            'SELECT ch.*, u.username, s.name as server_name 
             FROM command_history ch 
             LEFT JOIN users u ON ch.user_id = u.id 
             LEFT JOIN servers s ON ch.server_id = s.id 
             WHERE ch.status = \'active\'
             ORDER BY ch.executed_at DESC 
             LIMIT ?',
            [$limit]
        );
    }

    public function getById(int $id): ?array
    {
        return $this->db->fetch(
            'SELECT ch.*, u.username, s.name as server_name 
             FROM command_history ch 
             LEFT JOIN users u ON ch.user_id = u.id 
             LEFT JOIN servers s ON ch.server_id = s.id 
             WHERE ch.id = ? AND ch.status = \'active\'',
            [$id]
        );
    }

    public function clearHistory(int $serverId = null): int
    {
        if ($serverId) {
            return $this->db->update(
                'command_history',
                ['status' => 'deleted'],
                'server_id = ?',
                [$serverId]
            );
        }
        return $this->db->update(
            'command_history',
            ['status' => 'deleted'],
            '1=1'
        );
    }
}
