import os

from allauth.account.adapter import DefaultAccountAdapter
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from django.urls import reverse

from .models import ClientProfile


class TecvicoAccountAdapter(DefaultAccountAdapter):
    def get_login_redirect_url(self, request):
        return reverse("projects:dashboard")

    def get_signup_redirect_url(self, request):
        return reverse("projects:dashboard")


class TecvicoSocialAccountAdapter(DefaultSocialAccountAdapter):
    def save_user(self, request, sociallogin, form=None):
        user = super().save_user(request, sociallogin, form)
        self._apply_profile_names(user, sociallogin)
        user.save()
        ClientProfile.objects.get_or_create(user=user)
        return user

    def _apply_profile_names(self, user, sociallogin):
        extra_data = sociallogin.account.extra_data or {}
        if sociallogin.account.provider == "google":
            if not user.first_name:
                user.first_name = extra_data.get("given_name", "")
            if not user.last_name:
                user.last_name = extra_data.get("family_name", "")
            return
        if sociallogin.account.provider == "github" and not user.first_name:
            name = (extra_data.get("name") or "").strip()
            if name:
                parts = name.split(" ", 1)
                user.first_name = parts[0]
                user.last_name = parts[1] if len(parts) > 1 else ""
