import random
from datetime import datetime, timedelta
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_
from app.models.user.user_model import OTPVerification
from app.utils.email import email_service


class OTPService:
    """Service for handling OTP generation and verification"""
    
    def __init__(self, db: AsyncSession):
        self.db = db
    
    def _generate_otp(self) -> str:
        """Generate a 6-digit OTP code"""
        return str(random.randint(100000, 999999))
    
    async def create_and_send_otp(self, email: str) -> bool:
        """Create OTP and send to user email"""
        # Generate OTP code
        otp_code = self._generate_otp()
        
        # Set expiration time (10 minutes from now)
        expires_at = datetime.utcnow() + timedelta(minutes=10)
        
        # Save OTP to database
        otp_record = OTPVerification(
            email=email,
            otp_code=otp_code,
            is_used=False,
            expires_at=expires_at
        )
        
        self.db.add(otp_record)
        await self.db.commit()
        
        # Send OTP email
        email_sent = await email_service.send_otp_email(email, otp_code)
        
        # For development: print OTP to console if email fails
        if not email_sent:
            print(f"OTP for {email}: {otp_code}")
        
        return True
    
    async def verify_otp(self, email: str, otp_code: str) -> bool:
        """Verify OTP code for given email"""
        # Find valid OTP record
        stmt = select(OTPVerification).where(
            and_(
                OTPVerification.email == email,
                OTPVerification.otp_code == otp_code,
                OTPVerification.is_used == False,
                OTPVerification.expires_at > datetime.utcnow()
            )
        ).order_by(OTPVerification.created_at.desc())
        
        result = await self.db.execute(stmt)
        otp_record = result.scalar_one_or_none()
        
        if not otp_record:
            return False
        
        # Mark OTP as used
        otp_record.is_used = True
        await self.db.commit()
        
        return True
    
    async def invalidate_old_otps(self, email: str) -> None:
        """Invalidate all old OTPs for an email"""
        stmt = select(OTPVerification).where(
            and_(
                OTPVerification.email == email,
                OTPVerification.is_used == False
            )
        )
        
        result = await self.db.execute(stmt)
        old_otps = result.scalars().all()
        
        for otp in old_otps:
            otp.is_used = True
        
        await self.db.commit()

