import arrow

from api_modules.token.password_module import PasswordModule
from api_controllers.mongo.database import mongo_handler
from schemas import (
    Companies,
    Departments,
    Duty,
    Duties,
    Employees,
    People,
    Users,
    Staff,
    RelationshipDutyCompany,
)

def create_application_defaults(db_session):
    created_list, created_by, confirmed_by = [], "System", "System"
    active_row = dict(is_confirmed=True, active=True, deleted=False, is_notification_send=True)
    Companies.set_session(db_session)
    Departments.set_session(db_session)
    Duties.set_session(db_session)
    Duty.set_session(db_session)
    Staff.set_session(db_session)
    People.set_session(db_session)
    Users.set_session(db_session)
    Employees.set_session(db_session)
    RelationshipDutyCompany.set_session(db_session)

    company_management = Companies.query.filter_by(company_tag="Evyos",).first()
    if not company_management:
        company_management = Companies.find_or_create(
            **{
                "formal_name": "Evyos LTD",
                "public_name": "Evyos Verimlilik Sistemleri",
                "company_type": "LTD",
                "commercial_type": "Commercial",
                "tax_no": "123132123132",
                "company_tag": "Evyos",
                "default_lang_type": "TR",
                "default_money_type": "TL",
                "is_commercial": True,
                "is_confirmed": True,
            }
        )
        created_list.append(company_management)
    else:
        print(f"Company Management Found {company_management.to_dict()}")
    company_id, company_uu_id = company_management.id, str(company_management.uu_id)

    execution = Departments.query.filter_by(department_code="EO001", company_id=company_id).first()
    if not execution:
        execution = Departments.create(
            department_name="Execution Office",
            department_code="EO001",
            company_id=company_id,
            company_uu_id=str(company_uu_id),
            **active_row,
        )
        created_list.append(execution)
    else: 
        print(f"Execution Found {execution.to_dict()}")
    
    gen_man = Departments.query.filter_by(department_code="GM001", company_id=company_id).first()
    if not gen_man:
        gen_man = Departments.create(
            department_name="General Manager Example",
            department_code="GM001",
            company_id=company_id,
            company_uu_id=str(company_uu_id),
            **active_row,
        )
        created_list.append(gen_man)
    else: 
        print(f"General Manager Found {gen_man.to_dict()}")

    it_dept = Departments.query.filter_by(department_code="ITD001", company_id=company_id).first()
    if not it_dept:
        it_dept = Departments.create(
            department_name="IT Department",
            department_code="ITD001",
            company_id=company_id,
            company_uu_id=str(company_uu_id),
            **active_row,
        )
        created_list.append(it_dept)
    else: 
        print(f"IT Department Found {it_dept.to_dict()}")

    gen_duty = Duty.query.filter_by(duty_code="GM0001").first()
    if not gen_duty:
        gen_duty = Duty.create(
            duty_name="General Manager",
            duty_code="GM0001",
            duty_description="General Manager",
            **active_row,
        )
        created_list.append(gen_duty)
    else: 
        print(f"General Manager Found {gen_duty.to_dict()}")

    bm_duty = Duty.query.filter_by(duty_code="BM0001").first()
    if not bm_duty:
        bm_duty = Duty.create(
            duty_name="Business Manager",
            duty_code="BM0001",
            duty_description="Business Manager",
            **active_row,
        )
        created_list.append(bm_duty)
    else: 
        print(f"Business Manager Found {bm_duty.to_dict()}")
    it_duty = Duty.query.filter_by(duty_code="IT0001").first()
    if not it_duty:
        it_duty = Duty.create(
            duty_name="IT Manager",
            duty_code="IT0001",
            duty_description="IT Manager",
            **active_row,
        )
        created_list.append(it_duty)
    else: 
        print(f"IT Manager Found {it_duty.to_dict()}")
    bulk_duty = Duty.query.filter_by(duty_code="BULK").first()
    if not bulk_duty:
        bulk_duty = Duty.create(
            duty_name="BULK",
            duty_code="BULK",
            duty_description="BULK RECORDS OF THE COMPANY",
            **active_row,
        )
        created_list.append(bulk_duty)
    else: 
        print(f"Bulk Duty Found {bulk_duty.to_dict()}")
    occu_duty = Duty.query.filter_by(duty_code="OCCUPANT").first()
    if not occu_duty:
        occu_duty = Duty.create(
            duty_name="OCCUPANT",
            duty_code="OCCUPANT",
            duty_description="OCCUPANT RECORDS OF THE COMPANY",
            **active_row,
        )
        created_list.append(occu_duty)
    else: 
        print(f"Occupant Duty Found {occu_duty.to_dict()}")

    duties_gen_man = Duties.query.filter_by(company_id=company_id, duties_id=gen_duty.id, department_id=gen_man.id).first()
    if not duties_gen_man:
        duties_gen_man = Duties.create(
            company_id=company_id,
            company_uu_id=str(company_uu_id),
            duties_id=gen_duty.id,
            duties_uu_id=str(gen_duty.uu_id),
            department_id=gen_man.id,
            department_uu_id=str(gen_man.uu_id),
            **active_row,
        )
        created_list.append(duties_gen_man)
    else: 
        print(f"Duties General Manager Found {duties_gen_man.to_dict()}")

    duties_created_bm = Duties.query.filter_by(company_id=company_id, duties_id=bm_duty.id, department_id=execution.id).first()
    if not duties_created_bm:
        duties_created_bm = Duties.create(
            company_id=company_id,
            company_uu_id=str(company_uu_id),
            duties_id=bm_duty.id,
            duties_uu_id=str(bm_duty.uu_id),
            department_id=execution.id,
            department_uu_id=str(execution.uu_id),
            **active_row,
        )
        created_list.append(duties_created_bm)
    else: 
        print(f"Duties Business Manager Found {duties_created_bm.to_dict()}")
    duties_created_it = Duties.query.filter_by(company_id=company_id, duties_id=bulk_duty.id, department_id=execution.id).first()
    if not duties_created_it:
        duties_created_it = Duties.create(
            company_id=company_id,
            company_uu_id=str(company_uu_id),
            duties_id=bulk_duty.id,
            duties_uu_id=str(bulk_duty.uu_id),
            department_id=execution.id,
            department_uu_id=str(execution.uu_id),
            **active_row,
        )
        created_list.append(duties_created_it)
    else: 
        print(f"Duties Bulk Found {duties_created_it.to_dict()}")
    duties_created_occupant = Duties.query.filter_by(company_id=company_id, duties_id=occu_duty.id, department_id=execution.id).first()
    if not duties_created_occupant:
        duties_created_occupant = Duties.create(
            company_id=company_id,
            company_uu_id=str(company_uu_id),
            duties_id=occu_duty.id,
            duties_uu_id=str(occu_duty.uu_id),
            department_id=execution.id,
            department_uu_id=str(execution.uu_id),
            **active_row,
        )
        created_list.append(duties_created_occupant)
    else: 
        print(f"Duties Occupant Found {duties_created_occupant.to_dict()}")
    bulk_duty = Duty.query.filter_by(duty_code="BULK").first()
    if not bulk_duty:
        bulk_duty = Duty.create(
            duty_name="BULK",
            duty_code="BULK",
            duty_description="BULK RECORDS OF THE COMPANY",
            **active_row,
        )
        created_list.append(bulk_duty)
    else: 
        print(f"Bulk Duty Found {bulk_duty.to_dict()}")
    it_dept = Departments.query.filter_by(department_code="ITD001", company_id=company_id).first()
    if not it_dept:
        it_dept = Departments.create(
            department_name="IT Department",
            department_code="ITD001",
            company_id=company_id,
            company_uu_id=str(company_uu_id),
            **active_row,
        )
        created_list.append(it_dept)
    else: 
        print(f"IT Department Found {it_dept.to_dict()}")
    created_duty = Duty.query.filter_by(duty_code="DM").first()
    if not created_duty:
        created_duty = Duty.create(
            duty_name="Database Manager",
            duty_code="DM",
            duty_description="Database Manager",
            created_by=created_by,
            confirmed_by=confirmed_by,
            is_confirmed=True,
            active=True,
            deleted=False,
            is_notification_send=True,
        )
        created_list.append(created_duty)
    created_duty = Duty.query.filter_by(duty_code="NM").first()
    if not created_duty:
        created_duty = Duty.create(
            duty_name="Network Manager",
            duty_code="NM",
            duty_description="Network Manager",
            created_by=created_by,
            confirmed_by=confirmed_by,
            is_confirmed=True,
            active=True,
            deleted=False,
            is_notification_send=True,
        )
        created_list.append(created_duty)
    application_manager_duty = Duty.query.filter_by(duty_code="AM").first()
    if not application_manager_duty:
        application_manager_duty = Duty.create(
            duty_name="Application Manager",
            duty_code="AM",
            duty_description="Application Manager",
            created_by=created_by,
            confirmed_by=confirmed_by,
            is_confirmed=True,
            active=True,
            deleted=False,
            is_notification_send=True,
        )
        created_list.append(application_manager_duty)
    application_super_user_duty = Duty.query.filter_by(duty_code="SUE").first()
    if not application_super_user_duty:
        application_super_user_duty = Duty.create(
            duty_name="Super User",
            duty_code="SUE",
            duty_description="Super User",
            created_by=created_by,
            confirmed_by=confirmed_by,
            **active_row,
        )
        created_list.append(application_super_user_duty)

    application_manager_duties = Duties.query.filter_by(
        department_id=it_dept.id,
        duties_id=application_manager_duty.id,
        company_id=company_id,
    ).first()
    if not application_manager_duties:
        application_manager_duties = Duties.create(
            department_id=it_dept.id,
            department_uu_id=str(it_dept.uu_id),
            duties_id=application_manager_duty.id,
            duties_uu_id=str(application_manager_duty.uu_id),
            company_id=company_id,
            company_uu_id=str(company_uu_id),
            **active_row,
        )
        created_list.append(application_manager_duties)
    else:
        print(f"Application Manager Duties Found {application_manager_duties.to_dict()}")
    
    
    super_user_duties = Duties.query.filter_by(
        department_id=it_dept.id,
        duties_id=application_super_user_duty.id,
        company_id=company_id,
    ).first()
    if not super_user_duties:
        super_user_duties = Duties.create(
            department_id=it_dept.id,
            department_uu_id=str(it_dept.uu_id),
            duties_id=application_super_user_duty.id,
            duties_uu_id=str(application_manager_duty.uu_id),
            company_id=company_id,
            company_uu_id=str(company_uu_id),
            **active_row,
        )
        created_list.append(super_user_duties)
    else:
        print(f"Super User Duties Found {super_user_duties.to_dict()}")
        relation_super_user_duties = RelationshipDutyCompany.query.filter_by(
            duties_id=super_user_duties.id,
            owner_id=company_id,
            member_id=company_id,
        ).first()
        if not relation_super_user_duties:
            relation_super_user_duties = RelationshipDutyCompany.create(
                duties_id=super_user_duties.id,
                owner_id=company_id,
                member_id=company_id,
                parent_id=None,
                child_count=0,
                **active_row,
            )
            created_list.append(super_user_duties)
    
    relation_application_manager_duties = RelationshipDutyCompany.query.filter_by(
        duties_id=application_manager_duties.id,
        owner_id=company_id,
        member_id=company_id,
    ).first()
    if not relation_application_manager_duties:
        relation_application_manager_duties = RelationshipDutyCompany.create(
            duties_id=application_manager_duties.id,
            owner_id=company_id,
            member_id=company_id,
            parent_id=None,
            child_count=0,
            **active_row,
        )
        created_list.append(relation_application_manager_duties)

    app_manager = People.query.filter_by(
        person_tag="BAM-System",
    ).first()
    if not app_manager:
        app_manager = People.create(
            **{
                "person_tag": "BAM-System",
                "firstname": "Berkay Application Manager",
                "surname": "Karatay",
                "sex_code": "M",
                "middle_name": "",
                "father_name": "Father",
                "mother_name": "Mother",
                "country_code": "TR",
                "national_identity_id": "12312312312",
                "birth_place": "Ankara",
                "birth_date": "01.07.1990",
                "tax_no": "1231231231",
                **active_row,
            },
        )
        created_list.append(app_manager)
    else:
        print(f"Application Manager Found {app_manager.to_dict()}")

    sup_manager = People.query.filter_by(person_tag="BSU-System").first()
    if not sup_manager:
        sup_manager = People.create(
            **{
                "person_tag": "BSU-System",
                "firstname": "Berkay Super User",
                "surname": "Karatay",
                "sex_code": "M",
                "middle_name": "",
                "father_name": "Father",
                "mother_name": "Mother",
                "country_code": "TR",
                "national_identity_id": "12312312313",
                "birth_place": "Ankara",
                "birth_date": "01.07.1990",
                "tax_no": "1231231232",
                **active_row,
            },
        )
        created_list.append(sup_manager)
    else:
        print(f"Super User Found {sup_manager.to_dict()}")

    gen_manager_people = People.query.filter_by(person_tag="BM-System").first()
    if not gen_manager_people:
        gen_manager_people = People.create(
            **{
                "person_tag": "BM-System",
                "firstname": "Example General Manager",
                "surname": "Example",
                "sex_code": "M",
                "middle_name": "",
                "father_name": "Father",
                "mother_name": "Mother",
                "country_code": "TR",
                "national_identity_id": "12312312314",
                "birth_place": "Ankara",
                "birth_date": "01.07.1990",
                "tax_no": "1231231233",
                **active_row,
            },
        )
        created_list.append(gen_manager_people)
    else:
        print(f"General Manager Found {gen_manager_people.to_dict()}")

    application_manager_staff = Staff.query.filter_by(staff_code="AME", duties_id=application_manager_duties.id).first()
    if not application_manager_staff:
        application_manager_staff = Staff.create(
            **{
                "staff_code": "AME",
                "staff_name": "Application Manager Employee",
                "staff_description": "Application Manager Employee",
                "duties_id": application_manager_duties.id,
                "duties_uu_id": str(application_manager_duty.uu_id),
                **active_row,
            },
        )
        created_list.append(application_manager_staff)
    else:
        print(f"Application Manager Found {application_manager_staff.to_dict()}")

    super_user_staff = Staff.query.filter_by(staff_code="SUE", duties_id=super_user_duties.id).first()
    if not super_user_staff:
        super_user_staff = Staff.create(
            **{
                "staff_code": "SUE",
                "staff_name": "Super User Employee",
                "staff_description": "Super User Employee",
                "duties_id": super_user_duties.id,
                "duties_uu_id": str(super_user_duties.uu_id),
                **active_row,
            },
        )
        created_list.append(super_user_staff)
    else:
        print(f"Super User Found {super_user_staff.to_dict()}")
    
    gen_manager_staff = Staff.query.filter_by(staff_code="GME", duties_id=duties_gen_man.id).first()
    if not gen_manager_staff:
        gen_manager_staff = Staff.create(
            **{
                "staff_code": "GME",
                "staff_name": "General Manager Employee",
                "staff_description": "General Manager Employee",
                "duties_id": duties_gen_man.id,
                "duties_uu_id": str(duties_gen_man.uu_id),
                **active_row,
            },
        )
        created_list.append(gen_manager_staff)
    else:
        print(f"General Manager Found {gen_manager_staff.to_dict()}")

    application_manager_staff = Staff.query.filter_by(staff_code="AME", duties_id=application_manager_duty.id).first()
    if not application_manager_staff:
        application_manager_staff = Staff.create(
            **{
            "staff_code": "AME",
            "staff_name": "Application Manager Employee",
            "staff_description": "Application Manager Employee",
            "duties_id": application_manager_duty.id,
            "duties_uu_id": str(application_manager_duty.uu_id),
            **active_row,
            },
        )
        created_list.append(application_manager_staff)
    gen_man_staff = Staff.query.filter_by(staff_code="GME", duties_id=duties_gen_man.id).first()
    if not gen_man_staff:
        gen_man_staff = Staff.create(
            **{
            "staff_code": "GME",
            "staff_name": "General Manager Employee",
            "staff_description": "General Manager Employee",
            "duties_id": duties_gen_man.id,
            "duties_uu_id": str(gen_duty.uu_id),
            **active_row,
            },
        )
        created_list.append(gen_man_staff)
    
    gen_man_employee = Employees.query.filter_by(staff_id=gen_man_staff.id, people_id=gen_manager_people.id).first()
    if not gen_man_employee:
        gen_man_employee = Employees.create(
            staff_id=gen_man_staff.id,
            staff_uu_id=str(gen_man_staff.uu_id),
            people_id=gen_manager_people.id,
            people_uu_id=str(gen_manager_people.uu_id),
            **active_row,
        )
        created_list.append(gen_man_employee)

    app_manager_employee = Employees.query.filter_by(staff_id=application_manager_staff.id, people_id=app_manager.id).first()
    if not app_manager_employee:
        app_manager_employee = Employees.create(
            staff_id=application_manager_staff.id,
            staff_uu_id=str(application_manager_staff.uu_id),
            people_id=app_manager.id,
            people_uu_id=str(app_manager.uu_id),
            **active_row,
        )
        created_list.append(app_manager_employee)

    super_user_employee = Employees.query.filter_by(staff_id=super_user_staff.id, people_id=sup_manager.id).first()
    if not super_user_employee:
        super_user_employee = Employees.create(
            staff_id=super_user_staff.id,
            staff_uu_id=str(super_user_staff.uu_id),
            people_id=sup_manager.id,
            people_uu_id=str(sup_manager.uu_id),
            **active_row,
        )
        created_list.append(super_user_employee)

    gen_manager_user = Users.query.filter_by(person_id=gen_manager_people.id, user_tag=gen_manager_people.person_tag).first()
    if not gen_manager_user:
        gen_manager_user = Users.create(
            person_id=gen_manager_people.id,
            person_uu_id=str(gen_manager_people.uu_id),
            user_tag=gen_manager_people.person_tag,
            email="example.general@evyos.com.tr",
            phone_number="+901111111111",
            avatar="https://s.tmimgcdn.com/scr/800x500/276800/building-home-nature-logo-vector-template-3_276851-original.jpg",
            related_company=str(company_management.uu_id),
            **active_row,
        )
        created_list.append(gen_manager_user)
        gen_manager_user.password_expiry_begins = str(arrow.now())
        gen_manager_user.password_token = PasswordModule.generate_refresher_token()
        main_domain, collection_name = (
            "evyos.com.tr",
            f"{str(company_management.uu_id)}*Domain",
        )
        with mongo_handler.collection(collection_name) as mongo_engine:
            existing_record = mongo_engine.find_one(
                {"user_uu_id": str(gen_manager_user.uu_id)}
            )
            if not existing_record:
                mongo_engine.insert_one(
                    document={
                        "user_uu_id": str(gen_manager_user.uu_id),
                        "other_domains_list": [main_domain],
                        "main_domain": main_domain,
                        "modified_at": arrow.now().timestamp(),
                    }
                )
            else:
                mongo_engine.update_one(
                    {"user_uu_id": str(gen_manager_user.uu_id)},
                    {
                        "$set": {
                            "other_domains_list": [main_domain],
                            "main_domain": main_domain,
                            "modified_at": arrow.now().timestamp(),
                        }
                    },
                )

    app_manager_user = Users.query.filter_by(person_id=app_manager.id, user_tag=app_manager.person_tag).first()
    if not app_manager_user:
        app_manager_user = Users.create(
            person_id=app_manager.id,
            user_tag=app_manager.person_tag,
            email="karatay.berkay.man@evyos.com.tr",
            phone_number="+901111111111",
            avatar="https://s.tmimgcdn.com/scr/800x500/276800/building-home-nature-logo-vector-template-3_276851-original.jpg",
            related_company=str(company_management.uu_id),
            **active_row,
        )
        created_list.append(app_manager_user)
        app_manager_user.password_expiry_begins = str(arrow.now())
        app_manager_user.password_token = PasswordModule.generate_refresher_token()

        with mongo_handler.collection(collection_name) as mongo_engine:
            existing_record = mongo_engine.find_one(
                {"user_uu_id": str(app_manager_user.uu_id)}
            )
            if not existing_record:
                mongo_engine.insert_one(
                    document={
                        "user_uu_id": str(app_manager_user.uu_id),
                        "other_domains_list": [main_domain],
                        "main_domain": main_domain,
                        "modified_at": arrow.now().timestamp(),
                    }
                )
            else:
                mongo_engine.update_one(
                    {"user_uu_id": str(app_manager_user.uu_id)},
                    {
                        "$set": {
                            "other_domains_list": [main_domain],
                            "main_domain": main_domain,
                            "modified_at": arrow.now().timestamp(),
                        }
                    },
                )

    sup_manager_user = Users.query.filter_by(person_id=sup_manager.id, user_tag=sup_manager.person_tag).first()
    if not sup_manager_user:
        sup_manager_user = Users.create(
            person_id=sup_manager.id,
            user_tag=sup_manager.person_tag,
            email="karatay.berkay.sup@evyos.com.tr",
            phone_number="+901111111112",
            avatar="https://s.tmimgcdn.com/scr/800x500/276800/building-home-nature-logo-vector-template-3_276851-original.jpg",
            created_by=created_by,
            confirmed_by=confirmed_by,
            related_company=str(company_management.uu_id),
            **active_row,
        )
        created_list.append(sup_manager_user)

        sup_manager_user.password_expiry_begins = str(arrow.now())
        sup_manager_user.password_token = PasswordModule.generate_refresher_token()
        with mongo_handler.collection(collection_name) as mongo_engine:
            existing_record = mongo_engine.find_one(
                {"user_uu_id": str(sup_manager_employee.uu_id)}
            )
            if not existing_record:
                print("insert sup existing record", existing_record)
                mongo_engine.insert_one(
                    document={
                        "user_uu_id": str(sup_manager_employee.uu_id),
                        "other_domains_list": [main_domain, "management.com.tr"],
                        "main_domain": main_domain,
                        "modified_at": arrow.now().timestamp(),
                    }
                )
            else:
                print("update sup existing record", existing_record)
                # Optionally update the existing record if needed
                mongo_engine.update_one(
                    {"user_uu_id": str(sup_manager_employee.uu_id)},
                    {
                        "$set": {
                            "other_domains_list": [main_domain, "management.com.tr"],
                            "main_domain": main_domain,
                            "modified_at": arrow.now().timestamp(),
                        }
                    },
                )
        
    db_session.commit()
    print("All Defaults Create is now completed")
