from django_scopes import scope
from django.shortcuts import redirect
from django.urls import reverse
from account.models import Organization

class TenantMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if not request.user.is_authenticated:
            return self.get_response(request)

        active_org_id = request.session.get('active_org_id') # Laten we 'org' aanhouden ipv 'company'

        select_url = reverse('select_organization')
        logout_url = reverse('logout')
        exempt_urls = [select_url, logout_url]

        if not active_org_id and request.path not in exempt_urls:
            if first_org := request.user.organizations.first():
                active_org_id = str(first_org.id)
                request.session['active_org_id'] = active_org_id
            else:
                # @TODO: User doesn't have any organization -> Edge case!
                pass

        if active_org_id:
            try:
                org = Organization.objects.get(id=active_org_id, users=request.user)
                request.organization = org

                with scope(organization=org):
                    return self.get_response(request)

            except Organization.DoesNotExist:
                if 'active_org_id' in request.session:
                    del request.session['active_org_id']
                return redirect(reverse('dashboard'))

        return self.get_response(request)
