{% extends "admin/admin_base.html" %}

{% block title %}Автоматизация - API ключи и Webhooks{% endblock %}

{% block admin_content %}
<div class="container-fluid mt-4">
    <h1 class="mb-4">
        <i class="bi bi-robot"></i> Автоматизация
    </h1>
    
    <!-- Вкладки -->
    <ul class="nav nav-tabs mb-4" id="automationTabs" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="api-keys-tab" data-bs-toggle="tab" data-bs-target="#api-keys" type="button" role="tab">
                <i class="bi bi-key-fill"></i> API Ключи
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="webhooks-tab" data-bs-toggle="tab" data-bs-target="#webhooks" type="button" role="tab">
                <i class="bi bi-broadcast"></i> Webhooks
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="examples-tab" data-bs-toggle="tab" data-bs-target="#examples" type="button" role="tab">
                <i class="bi bi-code-square"></i> Примеры использования
            </button>
        </li>
    </ul>
    
    <div class="tab-content" id="automationTabContent">
        <!-- API Ключи -->
        <div class="tab-pane fade show active" id="api-keys" role="tabpanel">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h3>API Ключи</h3>
                <button class="btn btn-primary" onclick="showCreateApiKeyModal()">
                    <i class="bi bi-plus-circle"></i> Создать API ключ
                </button>
            </div>
            
            <div class="table-responsive">
                <table class="table table-striped" id="apiKeysTable">
                    <thead>
                        <tr>
                            <th>Название</th>
                            <th>Префикс</th>
                            <th>Описание</th>
                            <th>Разрешения</th>
                            <th>Статус</th>
                            <th>Последнее использование</th>
                            <th>Истекает</th>
                            <th>Действия</th>
                        </tr>
                    </thead>
                    <tbody id="apiKeysTableBody">
                        <tr>
                            <td colspan="8" class="text-center">Загрузка...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- Webhooks -->
        <div class="tab-pane fade" id="webhooks" role="tabpanel">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h3>Webhooks</h3>
                <button class="btn btn-primary" onclick="showCreateWebhookModal()">
                    <i class="bi bi-plus-circle"></i> Создать Webhook
                </button>
            </div>
            
            <div class="table-responsive">
                <table class="table table-striped" id="webhooksTable">
                    <thead>
                        <tr>
                            <th>Название</th>
                            <th>URL</th>
                            <th>Типы событий</th>
                            <th>Метод</th>
                            <th>Статус</th>
                            <th>Последнее обновление</th>
                            <th>Действия</th>
                        </tr>
                    </thead>
                    <tbody id="webhooksTableBody">
                        <tr>
                            <td colspan="7" class="text-center">Загрузка...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- Примеры использования -->
        <div class="tab-pane fade" id="examples" role="tabpanel">
            <h3>Примеры использования API</h3>
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">Python</h5>
                    <pre><code>import requests

API_KEY = "your-api-key-here"
BASE_URL = "https://gateway.example.com/api/v1"

headers = {
    "X-API-Key": API_KEY,
    "Content-Type": "application/json"
}

# Получение списка сервисов
response = requests.get(f"{BASE_URL}/admin/services/list", headers=headers)
services = response.json()
print(services)</code></pre>
                </div>
            </div>
            <div class="card mt-3">
                <div class="card-body">
                    <h5 class="card-title">JavaScript/Node.js</h5>
                    <pre><code>const axios = require('axios');

const client = axios.create({
    baseURL: 'https://gateway.example.com',
    headers: {
        'X-API-Key': 'your-api-key-here',
        'Content-Type': 'application/json'
    }
});

// Получение списка сервисов
const services = await client.get('/api/v1/admin/services/list');
console.log(services.data);</code></pre>
                </div>
            </div>
            <div class="card mt-3">
                <div class="card-body">
                    <h5 class="card-title">cURL</h5>
                    <pre><code>curl -H "X-API-Key: your-api-key-here" \
     https://gateway.example.com/api/v1/admin/services/list</code></pre>
                </div>
            </div>
            <div class="alert alert-info mt-3">
                <i class="bi bi-info-circle"></i>
                <strong>Подробнее:</strong> Полная документация с примерами доступна в файле <code>docs/api_examples.md</code>
            </div>
        </div>
    </div>
</div>

<!-- Модальное окно создания API ключа -->
<div class="modal fade" id="createApiKeyModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Создать API ключ</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="createApiKeyForm">
                    <div class="mb-3">
                        <label class="form-label">Название *</label>
                        <input type="text" class="form-control" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Описание</label>
                        <textarea class="form-control" name="description" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Разрешения (JSON массив)</label>
                        <input type="text" class="form-control" name="permissions" value='[]' placeholder='["service.view", "service.manage"]'>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Дата истечения</label>
                        <input type="datetime-local" class="form-control" name="expires_at">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
                <button type="button" class="btn btn-primary" onclick="createApiKey()">Создать</button>
            </div>
        </div>
    </div>
</div>

<!-- Модальное окно отображения API ключа -->
<div class="modal fade" id="showApiKeyModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">API ключ создан</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <i class="bi bi-exclamation-triangle"></i>
                    <strong>Важно!</strong> Сохраните этот ключ - он больше не будет показан.
                </div>
                <div class="mb-3">
                    <label class="form-label">API ключ:</label>
                    <div class="input-group">
                        <input type="text" class="form-control" id="apiKeyValue" readonly>
                        <button class="btn btn-outline-secondary" type="button" onclick="copyApiKey()">
                            <i class="bi bi-clipboard"></i> Копировать
                        </button>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Закрыть</button>
            </div>
        </div>
    </div>
</div>

<!-- Модальное окно создания Webhook -->
<div class="modal fade" id="createWebhookModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Создать Webhook</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="createWebhookForm">
                    <div class="mb-3">
                        <label class="form-label">Название *</label>
                        <input type="text" class="form-control" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">URL *</label>
                        <input type="url" class="form-control" name="url" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Типы событий (JSON массив) *</label>
                        <input type="text" class="form-control" name="event_types" value='["service_restart", "deployment_started"]' required>
                        <small class="form-text text-muted">Пример: ["service_restart", "deployment_started", "config_update"]</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">HTTP метод</label>
                        <select class="form-select" name="method">
                            <option value="POST" selected>POST</option>
                            <option value="PUT">PUT</option>
                            <option value="PATCH">PATCH</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Секрет для подписи</label>
                        <input type="text" class="form-control" name="secret" placeholder="Опционально">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Заголовки (JSON объект)</label>
                        <input type="text" class="form-control" name="headers" value='{}' placeholder='{"Authorization": "Bearer token"}'>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Количество повторов</label>
                                <input type="number" class="form-control" name="retry_count" value="3" min="1" max="10">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Таймаут (секунды)</label>
                                <input type="number" class="form-control" name="timeout" value="10" min="1" max="60">
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Описание</label>
                        <textarea class="form-control" name="description" rows="2"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
                <button type="button" class="btn btn-primary" onclick="createWebhook()">Создать</button>
            </div>
        </div>
    </div>
</div>

<!-- Модальное окно истории доставки Webhook -->
<div class="modal fade" id="webhookDeliveriesModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">История доставки Webhook</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>Тип события</th>
                                <th>Статус</th>
                                <th>Код ответа</th>
                                <th>Попытка</th>
                                <th>Время доставки</th>
                                <th>Ошибка</th>
                            </tr>
                        </thead>
                        <tbody id="webhookDeliveriesBody">
                            <tr>
                                <td colspan="6" class="text-center">Загрузка...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
            </div>
        </div>
    </div>
</div>

<script src="{{ url_for('static', filename='js/automation.js') }}"></script>
{% endblock %}
