terraform {
  required_providers {
    fusionauth = {
      source  = "FusionAuth/fusionauth"
      version = "0.1.111"
    }
  }
}

provider "fusionauth" {
  api_key = var.fusionauth_api_key
  host    = var.fusionauth_uri
}

resource "fusionauth_lambda" "google_reconcile" {
  depends_on = [var.wait_on]

  name = "Google Reconcile"
  type = "GoogleReconcile"

  body = <<EOT
/**
* This is the default Google reconcile, modify this to your liking. Modify the user
* and registration objects using the incoming values from the identity provider.
*
* @param {Object} user - the FusionAuth user
* @param {Object} registration - the FusionAuth user registration
* @param {Object} idToken - the decoded JSON payload returned by the Google Token Info API.
*/
function reconcile(user, registration, idToken) {
  // Un-comment this line to see the idToken object printed to the event log
  // console.info(JSON.stringify(idToken, null, 2));

  // The idToken is the response from the tokeninfo endpoint
  // https://developers.google.com/identity/sign-in/web/backend-auth#calling-the-tokeninfo-endpoint
  user.firstName = idToken.given_name;
  user.lastName = idToken.family_name;
  user.fullName = idToken.name;
  user.imageUrl = idToken.picture;
}
    EOT
}

resource "fusionauth_idp_google" "google" {
  depends_on = [var.wait_on]

  enabled             = true
  debug               = true
  client_id           = var.google_client_id
  client_secret       = var.google_client_secret
  button_text         = "Login with Google"
  scope               = "openid profile email"
  linking_strategy    = "LinkByEmail"
  login_method        = "UseRedirect"
  lambda_reconcile_id = fusionauth_lambda.google_reconcile.id

  dynamic "application_configuration" {
    for_each = var.applications
    content {
      application_id      = application_configuration.value.id
      create_registration = application_configuration.value.create_registration
      enabled             = application_configuration.value.enabled
    }
  }
}

output "identity_provider_id" {
  value = fusionauth_idp_google.google.id
}
