from pathlib import Path

from pydantic import BaseModel
from django.core import mail

from ichec_django_core.models import Member
from ichec_django_core.client import MemberIdentifierCreate, MemberDetail
from ichec_django_core.client.resources import create_members

from ichec_django_core.test import (
    AuthAPITestCase,
    setup_default_users_and_groups,
    add_group_permissions,
)


class Invite(BaseModel, frozen=True):
    user_first_name: str
    user_last_name: str
    user_email: str
    invite_type: str
    action_url: str | None
    resource_id: int | None


class TestInviteView(AuthAPITestCase):

    def setUp(self):
        self.url = "/api/members/"
        setup_default_users_and_groups()

        add_group_permissions(
            "members",
            Member,
            ["view_member"],
        )

        add_group_permissions(
            "admins",
            Member,
            [
                "view_member",
                "change_member",
                "add_member",
                "delete_member",
                "invite_member",
            ],
        )

    def test_request_invite(self):

        invite = Invite(
            user_first_name="User First Name",
            user_last_name="User Last Name",
            user_email="username@domain.com",
            invite_type="basic",
            action_url="post/registration/action",
            resource_id=-1,
        )

        self.authenticate("admin_user")
        response = self.client.post("/accounts/invite", invite.model_dump())
        self.assertEqual(response.status_code, 201, response.data)

        member = MemberDetail(**response.data)
        self.assertEqual(member.username, "username", response.data)
        self.assertEqual(member.verified, False, response.data)
        self.deauthenticate()

        self.assertEqual(len(mail.outbox), 1)
        action_prefix = "http://testserver/accounts/login"
        self.assertTrue(action_prefix in mail.outbox[0].body)
