defmodule BorutaWeb.CredentialControllerTest do
  use BorutaWeb.ConnCase

  import Boruta.Factory
  import BorutaIdentity.AccountsFixtures

  alias Boruta.Config
  alias Boruta.Ecto.Token
  alias Boruta.Internal.Signatures
  alias BorutaIdentity.Accounts.User

  setup %{conn: conn} do
    {:ok, conn: conn}
  end

  @tag :skip
  test "returns a credential with a valid credential type", %{conn: conn} do
    {_, public_jwk} = public_key_fixture() |> JOSE.JWK.from_pem() |> JOSE.JWK.to_map()

    signer =
      Joken.Signer.create("RS256", %{"pem" => private_key_fixture()}, %{
        "jwk" => public_jwk,
        "typ" => "openid4vci-proof+jwt"
      })

    {:ok, token, _claims} =
      Signatures.Token.generate_and_sign(
        %{
          "aud" => Config.issuer(),
          "iat" => :os.system_time(:seconds)
        },
        signer
      )

    proof = %{
      "proof_type" => "jwt",
      "jwt" => token
    }

    credential_params = %{
      "credential_identifier" => "VerifiableCredential",
      "format" => "jwt_vc",
      "proof" => proof
    }

    backend =
      BorutaIdentity.Factory.insert(:backend,
        verifiable_credentials: [
          %{
            "display" => %{
              "background_color" => "#53b29f",
              "logo" => %{
                "alt_text" => "Boruta PoC logo",
                "url" => "https://io.malach.it/assets/images/logo.png"
              },
              "name" => "Federation credential PoC",
              "text_color" => "#FFFFFF"
            },
            "credential_identifier" => "FederatedAttributes",
            "types" => "VerifiableCredential BorutaCredential",
            "format" => "jwt_vc",
            "claims" => "family_name"
          }
        ]
      )

    %User{id: sub} = user_fixture(%{backend: backend, metadata: %{"family_name" => "family_name"}})

    %Token{value: access_token} =
      insert(:token,
        sub: sub,
        authorization_details: [%{"credential_identifiers" => ["VerifiableCredential"]}]
      )

    conn =
      conn
      |> put_req_header("authorization", "Bearer #{access_token}")

    conn =
      post(
        conn,
        Routes.credential_path(conn, :credential),
        credential_params
      )

    assert %{"credential" => credential} = json_response(conn, 200)
    assert credential
  end

  @tag :skip
  test "returns a defered credential with a valid credential type", %{conn: conn} do
    {_, public_jwk} = public_key_fixture() |> JOSE.JWK.from_pem() |> JOSE.JWK.to_map()

    signer =
      Joken.Signer.create("RS256", %{"pem" => private_key_fixture()}, %{
        "jwk" => public_jwk,
        "typ" => "openid4vci-proof+jwt"
      })

    {:ok, token, _claims} =
      Signatures.Token.generate_and_sign(
        %{
          "aud" => Config.issuer(),
          "iat" => :os.system_time(:seconds)
        },
        signer
      )

    proof = %{
      "proof_type" => "jwt",
      "jwt" => token
    }

    credential_params = %{
      "credential_identifier" => "VerifiableCredential",
      "format" => "jwt_vc",
      "proof" => proof
    }

    backend =
      BorutaIdentity.Factory.insert(:backend,
        verifiable_credentials: [
          %{
            "display" => %{
              "background_color" => "#53b29f",
              "logo" => %{
                "alt_text" => "Boruta PoC logo",
                "url" => "https://io.malach.it/assets/images/logo.png"
              },
              "name" => "Federation credential PoC",
              "text_color" => "#FFFFFF"
            },
            "credential_identifier" => "FederatedAttributes",
            "types" => "VerifiableCredential BorutaCredential",
            "format" => "jwt_vc",
            "defered" => true,
            "claims" => "family_name"
          }
        ]
      )

    %User{id: sub} = user_fixture(%{backend: backend, metadata: %{"family_name" => "family_name"}})

    %Token{value: access_token} =
      insert(:token,
        sub: sub,
        authorization_details: [%{"credential_identifiers" => ["VerifiableCredential"]}]
      )

    conn =
      conn
      |> put_req_header("authorization", "Bearer #{access_token}")

    defered_conn =
      post(
        conn,
        Routes.credential_path(conn, :credential),
        credential_params
      )

    assert %{"acceptance_token" => acceptance_token} = json_response(defered_conn, 200)
    assert acceptance_token

    conn =
      post(
        conn,
        Routes.credential_path(conn, :defered_credential),
        credential_params
      )

    assert %{"credential" => credential} = json_response(conn, 200)
    assert credential
  end

  def public_key_fixture do
    "-----BEGIN RSA PUBLIC KEY-----\nMIIBCgKCAQEA1PaP/gbXix5itjRCaegvI/B3aFOeoxlwPPLvfLHGA4QfDmVOf8cU\n8OuZFAYzLArW3PnnwWWy39nVJOx42QRVGCGdUCmV7shDHRsr86+2DlL7pwUa9QyH\nsTj84fAJn2Fv9h9mqrIvUzAtEYRlGFvjVTGCwzEullpsB0GJafopUTFby8WdSq3d\nGLJBB1r+Q8QtZnAxxvolhwOmYkBkkidefmm48X7hFXL2cSJm2G7wQyinOey/U8xD\nZ68mgTakiqS2RtjnFD0dnpBl5CYTe4s6oZKEyFiFNiW4KkR1GVjsKwY9oC2tpyQ0\nAEUMvk9T9VdIltSIiAvOKlwFzL49cgwZDwIDAQAB\n-----END RSA PUBLIC KEY-----\n\n"
  end

  def private_key_fixture do
    "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEA1PaP/gbXix5itjRCaegvI/B3aFOeoxlwPPLvfLHGA4QfDmVO\nf8cU8OuZFAYzLArW3PnnwWWy39nVJOx42QRVGCGdUCmV7shDHRsr86+2DlL7pwUa\n9QyHsTj84fAJn2Fv9h9mqrIvUzAtEYRlGFvjVTGCwzEullpsB0GJafopUTFby8Wd\nSq3dGLJBB1r+Q8QtZnAxxvolhwOmYkBkkidefmm48X7hFXL2cSJm2G7wQyinOey/\nU8xDZ68mgTakiqS2RtjnFD0dnpBl5CYTe4s6oZKEyFiFNiW4KkR1GVjsKwY9oC2t\npyQ0AEUMvk9T9VdIltSIiAvOKlwFzL49cgwZDwIDAQABAoIBAG0dg/upL8k1IWiv\n8BNphrXIYLYQmiiBQTPJWZGvWIC2sl7i40yvCXjDjiRnZNK9HwgL94XtALCXYRFR\nJD41bRA3MO5A0HSPIWwJXwS10/cU56HVCNHjwKa6Rz/QiG2kNASMZEMzlvHtrjna\ndx36/sjI3HH8gh1BaTZyiuDE72SMkPbL838jfL1YY9uJ0u6hWFDbdn3sqPfJ6Cnz\n1cu0piT35nkilnIGCNYA0i3lyMeo4XrdXaAJdN9nnqbCi5ewQWqaHbrIIY5LTgzJ\nYlOr3IiecyokFxHCbULXle60u0KqXYgBHmlQJJr1Dj4c9AkQmefjC2jRMlhOrIzo\nIkIUeMECgYEA+MNLB+w6vv1ogqzM3M1OLt6bziWJCn+XkziuMrCiY9KeDD+S70+E\nhfbhM5RjCE3wxC/k59039laT973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