import uuid
import logging
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.models.identity import User, Person, SocialAccount, UserRole
from app.services.security_service import security_service

logger = logging.getLogger(__name__)

class SocialAuthService:
    @staticmethod
    async def get_or_create_social_user(
        db: AsyncSession, 
        provider: str, 
        social_id: str, 
        email: str, 
        first_name: str, 
        last_name: str
    ):
        """
        Social Step 1: Csak alapregisztráció. 
        Nincs slug generálás, nincs flotta. Megáll a KYC kapujában.
        """
        # 1. Meglévő Social kapcsolat ellenőrzése
        stmt = select(SocialAccount).where(
            SocialAccount.provider == provider, 
            SocialAccount.social_id == social_id
        )
        result = await db.execute(stmt)
        social_acc = result.scalar_one_or_none()

        if social_acc:
            stmt = select(User).where(User.id == social_acc.user_id)
            user_result = await db.execute(stmt)
            return user_result.scalar_one_or_none()

        # 2. Felhasználó keresése email alapján
        stmt = select(User).where(User.email == email)
        user_result = await db.execute(stmt)
        user = user_result.scalar_one_or_none()

        if not user:
            try:
                # Person rekord létrehozása a Google-től kapott nevekkel
                new_person = Person(
                    id_uuid=uuid.uuid4(),
                    first_name=first_name or "Google",
                    last_name=last_name or "User",
                    is_active=False
                )
                db.add(new_person)
                await db.flush()

                # User rekord (folder_slug nélkül!)
                user = User(
                    email=email,
                    hashed_password=None,
                    person_id=new_person.id,
                    role=UserRole.user,
                    is_active=False,
                    is_deleted=False,
                    preferred_language="hu",
                    region_code="HU"
                )
                db.add(user)
                await db.flush()

                await security_service.log_event(
                    db,
                    user_id=user.id,
                    action="USER_REGISTER_SOCIAL",
                    severity="info",
                    target_type="User",
                    target_id=str(user.id),
                    new_data={"email": email, "provider": provider}
                )
            except Exception as e:
                await db.rollback()
                logger.error(f"Social Registration Error: {str(e)}")
                raise e

        # 3. Összekötés
        new_social = SocialAccount(
            user_id=user.id,
            provider=provider,
            social_id=social_id,
            email=email
        )
        db.add(new_social)
        await db.commit()
        await db.refresh(user)
        return user