# flake8: noqa
# The Okta software accompanied by this notice is provided pursuant to the following terms:
# Copyright © 2025-Present, Okta, Inc.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
# License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS
# IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and limitations under the License.
# coding: utf-8

from http import HTTPStatus

import pytest

import okta.models as models
from okta.errors.okta_api_error import OktaAPIError
from tests.mocks import MockOktaClient


class TestInlineHooksResource:
    """
    Integration Tests for the Inline Hooks Resource
    """

    SDK_PREFIX = "python_sdk"

    @pytest.mark.vcr()
    @pytest.mark.asyncio
    async def test_create_get_inline_hook(self, fs):
        # Instantiate Mock Client
        client = MockOktaClient(fs)

        # Create Inline Hook
        inline_hook_model = models.InlineHook(
            **{
                "name": f"{TestInlineHooksResource.SDK_PREFIX} Test Inline Hook",
                "version": "1.0.0",
                "type": models.InlineHookType.COM_DOT_OKTA_DOT_OAUTH2_DOT_TOKENS_DOT_TRANSFORM,
                "channel": models.InlineHookChannel(
                    **{
                        "type": "HTTP",
                        "version": "1.0.0",
                        "model_config": models.InlineHookChannelConfig(
                            **{
                                "uri": "https://www.example.com/inlineHook",
                                "headers": [
                                    models.InlineHookChannelConfigHeaders(
                                        **{
                                            "key": "X-Test-Header",
                                            "value": "Test Header Value",
                                        }
                                    )
                                ],
                                "authScheme": models.InlineHookChannelConfigAuthScheme(
                                    **{
                                        "type": "HEADER",
                                        "key": "Authorization",
                                        "value": "Test-Api-Key",
                                    }
                                ),
                            }
                        ),
                    }
                ),
            }
        )

        try:
            created_inline_hook, _, err = await client.create_inline_hook(
                inline_hook_model
            )
            assert err is None
            assert isinstance(created_inline_hook, models.InlineHook)
            assert created_inline_hook.id
            assert created_inline_hook.name == inline_hook_model.name
            assert created_inline_hook.channel
            assert created_inline_hook.channel.model_config
            # assert created_inline_hook.channel.config.uri ==\
            #     inline_hook_model.channel.config.uri

            # Retrieve
            retrieved_inline_hook, _, err = await client.get_inline_hook(
                created_inline_hook.id
            )
            assert err is None
            assert isinstance(retrieved_inline_hook, models.InlineHook)
            assert retrieved_inline_hook.id == created_inline_hook.id
            assert retrieved_inline_hook.name == created_inline_hook.name

        finally:
            errors = []
            # Deactivate & Delete
            try:
                deactivated_inline_hook, _, err = await client.deactivate_inline_hook(
                    created_inline_hook.id
                )
                assert err is None
                assert isinstance(deactivated_inline_hook, models.InlineHook)
                assert deactivated_inline_hook.status == "INACTIVE"
            except Exception as exc:
                errors.append(exc)

            try:
                _, _, err = await client.delete_inline_hook(created_inline_hook.id)
                assert err is None
            except Exception as exc:
                errors.append(exc)
            assert len(errors) == 0

    @pytest.mark.vcr()
    @pytest.mark.asyncio
    async def test_update_inline_hook(self, fs):
        # Instantiate Mock Client
        client = MockOktaClient(fs)

        # Create Inline Hook
        inline_hook_model = models.InlineHook(
            **{
                "name": f"{TestInlineHooksResource.SDK_PREFIX} Test Inline Hook",
                "version": "1.0.0",
                "type": models.InlineHookType.COM_DOT_OKTA_DOT_OAUTH2_DOT_TOKENS_DOT_TRANSFORM.value,
                "channel": models.InlineHookChannelHttp(
                    **{
                        "type": "HTTP",
                        "version": "1.0.0",
                        "config": models.InlineHookChannelConfig(
                            **{
                                "uri": "https://www.example.com/inlineHook",
                                "headers": [
                                    models.InlineHookChannelConfigHeaders(
                                        **{
                                            "key": "X-Test-Header",
                                            "value": "Test Header Value",
                                        }
                                    )
                                ],
                                "authScheme": models.InlineHookChannelConfigAuthScheme(
                                    **{
                                        "type": "HEADER",
                                        "key": "Authorization",
                                        "value": "Test-Api-Key",
                                    }
                                ),
                            }
                        ),
                    }
                ),
            }
        )

        try:
            created_inline_hook, _, err = await client.create_inline_hook(
                inline_hook_model
            )
            assert err is None
            assert isinstance(created_inline_hook, models.InlineHook)
            assert created_inline_hook.id
            assert created_inline_hook.name == inline_hook_model.name
            assert created_inline_hook.channel
            assert created_inline_hook.channel.config
            assert (
                    created_inline_hook.channel.config.uri
                    == inline_hook_model.channel.config.uri
            )

            # Update
            updated_inline_hook_model = models.InlineHook(
                **{
                    "name": inline_hook_model.name + "UPDATE",
                    "version": "1.0.0",
                    "type": models.InlineHookType.COM_DOT_OKTA_DOT_OAUTH2_DOT_TOKENS_DOT_TRANSFORM.value,
                    "channel": models.InlineHookChannelHttp(
                        **{
                            "type": "HTTP",
                            "version": "1.0.0",
                            "config": models.InlineHookChannelConfig(
                                **{
                                    "uri": inline_hook_model.channel.config.uri
                                           + "UPDATE",
                                    "headers": [
                                        models.InlineHookChannelConfigHeaders(
                                            **{
                                                "key": "X-Test-Header",
                                                "value": "Test Header Value UPDATE",
                                            }
                                        )
                                    ],
                                    "authScheme": models.InlineHookChannelConfigAuthScheme(
                                        **{
                                            "type": "HEADER",
                                            "key": "Authorization",
                                            "value": "Test-Api-Key-UPDATE",
                                        }
                                    ),
                                }
                            ),
                        }
                    ),
                }
            )
            updated_inline_hook, _, err = await client.replace_inline_hook(
                created_inline_hook.id, updated_inline_hook_model
            )
            assert err is None
            assert updated_inline_hook.id == created_inline_hook.id
            assert updated_inline_hook.name == updated_inline_hook_model.name
            assert (
                    updated_inline_hook.channel.config.uri
                    == updated_inline_hook_model.channel.config.uri
            )

            # Retrieve
            retrieved_inline_hook, _, err = await client.get_inline_hook(
                created_inline_hook.id
            )
            assert err is None
            assert isinstance(retrieved_inline_hook, models.InlineHook)
            assert retrieved_inline_hook.id == created_inline_hook.id
            assert retrieved_inline_hook.name == updated_inline_hook.name
            assert retrieved_inline_hook.version == created_inline_hook.version
            assert (
                    retrieved_inline_hook.type
                    == models.InlineHookType.COM_DOT_OKTA_DOT_OAUTH2_DOT_TOKENS_DOT_TRANSFORM.value
            )
            assert (
                    retrieved_inline_hook.channel.config.uri
                    == updated_inline_hook.channel.config.uri
            )

        finally:
            errors = []
            # Deactivate & Delete
            try:
                deactivated_inline_hook, _, err = await client.deactivate_inline_hook(
                    created_inline_hook.id
                )
                assert err is None
                assert isinstance(deactivated_inline_hook, models.InlineHook)
                assert deactivated_inline_hook.status == "INACTIVE"
            except Exception as exc:
                errors.append(exc)

            try:
                _, _, err = await client.delete_inline_hook(created_inline_hook.id)
                assert err is None
            except Exception as exc:
                errors.append(exc)
            assert len(errors) == 0

    @pytest.mark.vcr()
    @pytest.mark.asyncio
    async def test_delete_inline_hook(self, fs):
        # Instantiate Mock Client
        client = MockOktaClient(fs)

        # Create Inline Hook
        inline_hook_model = models.InlineHook(
            **{
                "name": f"{TestInlineHooksResource.SDK_PREFIX} Test Inline Hook",
                "version": "1.0.0",
                "type": models.InlineHookType.COM_DOT_OKTA_DOT_OAUTH2_DOT_TOKENS_DOT_TRANSFORM,
                "channel": models.InlineHookChannel(
                    **{
                        "type": "HTTP",
                        "version": "1.0.0",
                        "model_config": models.InlineHookChannelConfig(
                            **{
                                "uri": "https://www.example.com/inlineHook",
                                "headers": [
                                    models.InlineHookChannelConfigHeaders(
                                        **{
                                            "key": "X-Test-Header",
                                            "value": "Test Header Value",
                                        }
                                    )
                                ],
                                "authScheme": models.InlineHookChannelConfigAuthScheme(
                                    **{
                                        "type": "HEADER",
                                        "key": "Authorization",
                                        "value": "Test-Api-Key",
                                    }
                                ),
                            }
                        ),
                    }
                ),
            }
        )

        try:
            created_inline_hook, _, err = await client.create_inline_hook(
                inline_hook_model
            )
            assert err is None
            assert isinstance(created_inline_hook, models.InlineHook)
            assert created_inline_hook.id
            assert created_inline_hook.name == inline_hook_model.name
            assert created_inline_hook.channel
            assert created_inline_hook.channel.model_config
            # assert created_inline_hook.channel.config.uri ==\
            #     inline_hook_model.channel.config.uri

            # Deactivate & Delete
            deactivated_inline_hook, _, err = await client.deactivate_inline_hook(
                created_inline_hook.id
            )
            assert err is None
            assert isinstance(deactivated_inline_hook, models.InlineHook)
            assert deactivated_inline_hook.status == "INACTIVE"

            _, _, err = await client.delete_inline_hook(created_inline_hook.id)
            assert err is None

            # Retrieve
            retrieved_inline_hook, resp, err = await client.get_inline_hook(
                created_inline_hook.id
            )
            assert err is not None
            assert isinstance(err, OktaAPIError)
            assert resp.status == HTTPStatus.NOT_FOUND
            assert retrieved_inline_hook is None
        finally:
            # Deactivate & Delete
            try:
                _, _, err = await client.deactivate_inline_hook(created_inline_hook.id)
            except Exception:
                pass
            try:
                _, _, err = await client.delete_inline_hook(created_inline_hook.id)
            except Exception:
                pass

    @pytest.mark.vcr()
    @pytest.mark.asyncio
    async def test_activate_deactivate_inline_hook(self, fs):
        # Instantiate Mock Client
        client = MockOktaClient(fs)

        # Create Inline Hook
        inline_hook_model = models.InlineHook(
            **{
                "name": f"{TestInlineHooksResource.SDK_PREFIX} Test Inline Hook",
                "version": "1.0.0",
                "type": models.InlineHookType.COM_DOT_OKTA_DOT_OAUTH2_DOT_TOKENS_DOT_TRANSFORM,
                "channel": models.InlineHookChannel(
                    **{
                        "type": "HTTP",
                        "version": "1.0.0",
                        "model_config": models.InlineHookChannelConfig(
                            **{
                                "uri": "https://www.example.com/inlineHook",
                                "headers": [
                                    models.InlineHookChannelConfigHeaders(
                                        **{
                                            "key": "X-Test-Header",
                                            "value": "Test Header Value",
                                        }
                                    )
                                ],
                                "authScheme": models.InlineHookChannelConfigAuthScheme(
                                    **{
                                        "type": "HEADER",
                                        "key": "Authorization",
                                        "value": "Test-Api-Key",
                                    }
                                ),
                            }
                        ),
                    }
                ),
            }
        )

        try:
            created_inline_hook, _, err = await client.create_inline_hook(
                inline_hook_model
            )
            assert err is None
            assert isinstance(created_inline_hook, models.InlineHook)
            assert created_inline_hook.id
            assert created_inline_hook.name == inline_hook_model.name
            assert created_inline_hook.channel
            assert created_inline_hook.channel.model_config
            # assert created_inline_hook.channel.model_config.uri ==\
            #     inline_hook_model.channel.model_config.uri
            assert created_inline_hook.status == "ACTIVE"

            # Deactivate
            deactivated_inline_hook, _, err = await client.deactivate_inline_hook(
                created_inline_hook.id
            )
            assert err is None
            assert isinstance(deactivated_inline_hook, models.InlineHook)
            assert deactivated_inline_hook.status == "INACTIVE"

            # Retrieve
            retrieved_inline_hook, _, err = await client.get_inline_hook(
                created_inline_hook.id
            )
            assert err is None
            assert retrieved_inline_hook.status == "INACTIVE"

            # Activate
            activated_inline_hook, _, err = await client.activate_inline_hook(
                created_inline_hook.id
            )
            assert err is None
            assert isinstance(activated_inline_hook, models.InlineHook)
            assert activated_inline_hook.status == "ACTIVE"

            # Retrieve
            retrieved_inline_hook, _, err = await client.get_inline_hook(
                created_inline_hook.id
            )
            assert err is None
            assert retrieved_inline_hook.status == "ACTIVE"

        finally:
            errors = []
            # Delete & Deactivate
            try:
                _, _, err = await client.deactivate_inline_hook(created_inline_hook.id)
                assert err is None
            except Exception as exc:
                errors.append(exc)
            try:
                _, _, err = await client.delete_inline_hook(created_inline_hook.id)
                assert err is None
            except Exception as exc:
                errors.append(exc)
            assert len(errors) == 0

    @pytest.mark.vcr()
    @pytest.mark.asyncio
    async def test_list_inline_hooks(self, fs):
        # Instantiate Mock Client
        client = MockOktaClient(fs)

        try:
            # Create Inline Hooks
            NUMBER_OF_HOOKS = 3
            created_inline_hooks = []
            for index in range(NUMBER_OF_HOOKS):
                inline_hook_model = models.InlineHook(
                    **{
                        "name": f"{TestInlineHooksResource.SDK_PREFIX} IH{index}",
                        "version": "1.0.0",
                        "type": models.InlineHookType.COM_DOT_OKTA_DOT_OAUTH2_DOT_TOKENS_DOT_TRANSFORM,
                        "channel": models.InlineHookChannel(
                            **{
                                "type": "HTTP",
                                "version": "1.0.0",
                                "model_config": models.InlineHookChannelConfig(
                                    **{
                                        "uri": "https://www.example.com/inlineHook",
                                        "headers": [
                                            models.InlineHookChannelConfigHeaders(
                                                **{
                                                    "key": "X-Test-Header",
                                                    "value": f"Test Header {index}",
                                                }
                                            )
                                        ],
                                        "authScheme": models.InlineHookChannelConfigAuthScheme(
                                            **{
                                                "type": "HEADER",
                                                "key": "Authorization",
                                                "value": f"Test-Api-Key-{index}",
                                            }
                                        ),
                                    }
                                ),
                            }
                        ),
                    }
                )

                created_inline_hook, _, err = await client.create_inline_hook(
                    inline_hook_model
                )
                assert err is None
                created_inline_hooks.append(created_inline_hook.id)
                assert isinstance(created_inline_hook, models.InlineHook)
                assert created_inline_hook.id
                assert created_inline_hook.name == inline_hook_model.name
                assert created_inline_hook.channel
                assert created_inline_hook.channel.model_config
                # assert created_inline_hook.channel.config.uri ==\
                #     inline_hook_model.channel.config.uri

            # List
            all_inline_hooks, _, err = await client.list_inline_hooks()
            assert err is None
            assert isinstance(all_inline_hooks, list)
            for inline_hook_id in created_inline_hooks:
                assert next((ih for ih in all_inline_hooks if ih.id == inline_hook_id))

        finally:
            errors = []
            # Deactivate & Delete
            for inline_hook_id in created_inline_hooks:
                try:
                    _, _, err = await client.deactivate_inline_hook(inline_hook_id)
                    assert err is None
                except Exception as exc:
                    errors.append(exc)
                try:
                    _, _, err = await client.delete_inline_hook(inline_hook_id)
                    assert err is None
                except Exception as exc:
                    errors.append(exc)
            assert len(errors) == 0
