{% extends 'base.html' %}
{% from "macros.html" import render_field %}

{% block title %}Generate Chat API Key{% endblock %}

{% block content_title %}Generate Chat API Key{% endblock %}
{% block content_description %}Generate an API key to enable chat.{% endblock %}

{% block content %}
    <!-- Bootstrap Modal HTML for API Key Registration -->
    <div class="modal fade" id="confirmModal" tabindex="-1" role="dialog" aria-labelledby="confirmModalLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="confirmModalLabel">Confirm New API Key</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <div id="confirmation-message">
              There is already an API key defined for this tenant. Are you sure you want to generate a new API key? This will require updating the key in all locations using the chat interface.
            </div>
            <div id="api-key-message" style="display:none;">
              <p>New API Key:</p>
              <p id="new-api-key" style="font-weight: bold;"></p>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
            <button type="button" class="btn btn-primary" id="confirmNewKeyBtn">Confirm</button>
          </div>
        </div>
      </div>
    </div>
{% endblock %}
{% block content_footer %}
{% endblock %}
{% block scripts %}
<script>
    // Trigger the modal when the user tries to generate a new API key
    function promptForNewApiKey() {
        $('#confirmModal').modal('show');
    }

    // Handle the confirmation button click
    document.getElementById('confirmNewKeyBtn').addEventListener('click', function () {
        generateNewApiKey();
    });

    function generateNewApiKey() {
        // Make an AJAX request to your back-end to generate the new API key
        $.ajax({
            url: '/generate-api-key',
            type: 'POST',
            data: JSON.stringify({ tenant_id: tenantId }),  // Pass the tenant ID as needed
            contentType: 'application/json',
            success: function(response) {
                // Display the new API key in the modal
                $('#confirmation-message').hide();
                $('#api-key-message').show();
                $('#new-api-key').text(response.new_api_key);
            },
            error: function(error) {
                alert('Error generating new API key: ' + error.responseText);
            }
        });
    }
</script>
{% endblock %}
