from typing import Union

from fastapi import status
from fastapi.responses import JSONResponse

from api_validations.validations_response import PeopleListResponse
from api_validations.validations_request import InsertPerson, UpdateUsers
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from ApiServices.api_handlers import AlchemyJsonResponse
from databases import (
    People,
    Users,
    Companies,
)


class PeopleListEventMethods(MethodToEvent):

    event_type = "SELECT"
    __event_keys__ = {
        "0a05f03c-6ed8-4230-a4ff-6e7cf886909b": "super_users_people_list",
        "b5612538-0445-4a4a-ab13-d2a06037f7a5": "sales_users_people_list",
        "25cbbaf8-117a-470f-a844-2cfc70f71dde": "human_resources_users_people_list",
        "cdf62f06-ec50-40de-b19e-adb3dd34bb95": "people_list_only_occupant_tenant_or_owner",
    }
    __event_validation__ = {
        "0a05f03c-6ed8-4230-a4ff-6e7cf886909b": PeopleListResponse,
        "b5612538-0445-4a4a-ab13-d2a06037f7a5": None,
        "25cbbaf8-117a-470f-a844-2cfc70f71dde": None,
        "cdf62f06-ec50-40de-b19e-adb3dd34bb95": None,
    }

    @classmethod
    def super_users_people_list(
        cls, list_options, token_dict: Union[EmployeeTokenObject, OccupantTokenObject]
    ):
        records = []
        if isinstance(token_dict, EmployeeTokenObject):
            People.pre_query = People.select_action(
                duty_id_list=[
                    token_dict.selected_company.duty_id,
                    token_dict.selected_company.bulk_duties_id,
                ],
            )
            People.filter_attr = list_options
            records = People.filter_all()
        elif isinstance(token_dict, OccupantTokenObject):
            related_users = Users.filter_all(
                Users.related_company
                == token_dict.selected_occupant.responsible_company_id,
            ).data
            People.pre_query = People.filter_all(
                People.id.in_([user.person_id for user in related_users]),
            ).query
            People.filter_attr = list_options
            records = People.filter_all()
        return AlchemyJsonResponse(
            completed=True,
            message="People are listed successfully",
            result=records,
            cls_object=People,
            filter_attributes=list_options,
            response_model=PeopleListResponse,
        )

    @classmethod
    def sales_users_people_list(
        cls,
        list_options,
        token_dict: EmployeeTokenObject,
    ):
        People.filter_attr = list_options
        records = People.filter_all().data
        return AlchemyJsonResponse(
            completed=True,
            message="People are listed successfully",
            result=records,
        )

    @classmethod
    def human_resources_users_people_list(
        cls,
        list_options,
        token_dict: EmployeeTokenObject,
    ):
        if isinstance(token_dict, EmployeeTokenObject):
            People.filter_attr = list_options
            records = People.filter_all().data
        return AlchemyJsonResponse(
            completed=True,
            message="People are listed successfully",
            result=records,
        )


class PeopleCreateEventMethods(MethodToEvent):

    event_type = "CREATE"
    __event_keys__ = {
        "2d1513f4-44ed-4fa3-84d1-dfbd0eadf9a1": "people_create",
    }
    __event_validation__ = {
        "2d1513f4-44ed-4fa3-84d1-dfbd0eadf9a1": InsertPerson,
    }

    @classmethod
    def people_create(
        cls,
        data: InsertPerson,
        token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
    ):
        if isinstance(token_dict, EmployeeTokenObject):
            created_user = People.create_action(data=data, token=token_dict)
            People.save()
        elif isinstance(token_dict, OccupantTokenObject):
            created_user = People.create_action(data=data, token=token_dict)
            People.save()
        return JSONResponse(
            content={
                "completed": True,
                "message": "Create User record",
                "data": created_user.get_dict(),
            },
            status_code=status.HTTP_200_OK,
        )


class PeopleUpdateEventMethods(MethodToEvent):

    event_type = "UPDATE"
    __event_keys__ = {
        "e05cf22c-16c4-450b-86c8-417896a26afc": "people_update",
    }
    __event_validation__ = {"e05cf22c-16c4-450b-86c8-417896a26afc": UpdateUsers}

    @classmethod
    def people_update(
        cls,
        data: UpdateUsers,
        user_uu_id: str,
        token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
    ):
        data_dict = data.excluded_dump()
        if isinstance(token_dict, EmployeeTokenObject):
            find_one_user = Users.filter_one(
                Users.uu_id == user_uu_id,
            ).data
            access_authorized_company = Companies.select_action(
                duty_id_list=[
                    token_dict.selected_company.duty_id,
                    token_dict.selected_company.bulk_duties_id,
                ],
            )
            if access_authorized_company.count:
                updated_user = find_one_user.update(**data_dict)
                Users.save()
                return JSONResponse(
                    content={
                        "completed": True,
                        "message": "Update User record",
                        "data": updated_user,
                    },
                    status_code=status.HTTP_200_OK,
                )
        elif isinstance(token_dict, OccupantTokenObject):
            find_one_user = People.filter_one(
                People.uu_id == user_uu_id,
            ).data
            access_authorized_company = Companies.select_action(
                duty_id_list=[getattr(token_dict, "duty_id")],
                filter_expr=[Companies.id == find_one_user.id],
            )
            if access_authorized_company.count:
                data_dict = data.excluded_dump()
                updated_user = find_one_user.update(**data_dict)
                People.save()
        return JSONResponse(
            content={"completed": True, "message": "Update User record", "data": {}},
            status_code=status.HTTP_200_OK,
        )


class PeoplePatchEventMethods(MethodToEvent):

    event_type = "PATCH"
    __event_keys__ = {
        "3ae16d66-090b-4d27-b567-cce1b10a1c3b": "people_patch",
    }
    __event_validation__ = {"3ae16d66-090b-4d27-b567-cce1b10a1c3b": None}

    @classmethod
    def people_patch(cls):
        return


class PeopleDeleteEventMethods(MethodToEvent):

    event_type = "DELETE"
    __event_keys__ = {
        "7f84c7a2-a120-4867-90d4-6767a41320db": "people_delete",
    }
    __event_validation__ = {"7f84c7a2-a120-4867-90d4-6767a41320db": None}


PeopleListEventMethod = PeopleListEventMethods(
    action=ActionsSchema(endpoint="/people/list")
)
PeopleCreateEventMethod = PeopleCreateEventMethods(
    action=ActionsSchema(endpoint="/people/create")
)
PeopleUpdateEventMethod = PeopleUpdateEventMethods(
    action=ActionsSchema(endpoint="/people/update")
)
PeoplePatchEventMethod = PeoplePatchEventMethods(
    action=ActionsSchema(endpoint="/people/patch")
)
