# /opt/docker/dev/service_finder/backend/app/services/social_auth_service.py
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):
        """ 
        LOGIKA MEGŐRIZVE: Step 1 regisztráció slug és flotta nélkül. 
        """
        # 1. Meglévő fiók ellenőrzése
        stmt = select(SocialAccount).where(SocialAccount.provider == provider, SocialAccount.social_id == social_id)
        social_acc = (await db.execute(stmt)).scalar_one_or_none()

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

        # 2. Új Identity és User (Step 1)
        stmt_u = select(User).where(User.email == email)
        user = (await db.execute(stmt_u)).scalar_one_or_none()

        if not user:
            new_person = Person(first_name=first_name or "Social", last_name=last_name or "User", is_active=False)
            db.add(new_person)
            await db.flush()

            user = User(email=email, person_id=new_person.id, role=UserRole.user, is_active=False)
            db.add(user)
            await db.flush()

            await security_service.log_event(db, user.id, "USER_REGISTER_SOCIAL", "info", target_type="User", target_id=str(user.id))

        # 3. Kapcsolat rögzítése
        db.add(SocialAccount(user_id=user.id, provider=provider, social_id=social_id, email=email))
        await db.commit()
        await db.refresh(user)
        return user