<?php

namespace Drupal\miniorange_webauthn\Form;

use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\Core\Utility\Error;
use Drupal\miniorange_2fa\MoAuthUtilities;
use Drupal\user\UserInterface;
use Drupal\miniorange_webauthn\Entity\MoWebauthnCredential;

/**
 * Delete WebAuthn Credential Form.
 */
class DeleteCredentialForm extends ConfirmFormBase {

  /**
   * The user entity.
   *
   * @var UserInterface
   */
  protected UserInterface $user;

  /**
   * The WebAuthn Credential entity.
   *
   * @var MoWebauthnCredential
   */
  protected MoWebauthnCredential $webauthnCredential;

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'mo_webauthn_delete_credential_form';
  }

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return $this->t('Delete WebAuthn Device @label?', ['@label' => $this->webauthnCredential->getLabel()]);
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return new Url('mo_webauthn.read_configuration', ['user' => $this->user->id()]);
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, UserInterface $user = NULL, MoWebauthnCredential $id = NULL) {
    $this->user = $user;
    $this->webauthnCredential = $id;
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $label = $this->webauthnCredential->getLabel();
    $uid = $this->user->id();
    try {
      $storage = \Drupal::entityTypeManager()->getStorage('mo_webauthn_credential');
      $credentials = $storage->getQuery()
        ->condition('uid', $uid)
        ->accessCheck(FALSE)
        ->count()
        ->execute();

      $user_attributes = MoAuthUtilities::get_users_custom_attribute($uid);
      $active_method = !empty($user_attributes) && isset($user_attributes[0]->activated_auth_methods) ? $user_attributes[0]->activated_auth_methods : NULL;
      if ($credentials <= 1 && $active_method === 'WEB AUTHN') {
        $this->messenger()->addError($this->t(
          'There should be at least one key as your active method is WebAuthn. To delete this, change your active method.'
        ));
        $form_state->setRedirectUrl($this->getCancelUrl());
        return;
      }
      $this->webauthnCredential->delete();
      $this->messenger()->addStatus($this->t(
        'Successfully deleted WebAuthn device [@label].',
        ['@label' => $label]
      ));
      $form_state->setRedirectUrl($this->getCancelUrl());
    }
    catch (\Exception $exception) {
      Error::logException($this->logger('miniorange_webauthn'), $exception);
      $this->messenger()->addError($this->t('Failed to delete WebAuthn device [@label].', ['@label' => $label]
      ));
    }
  }
}
