"""
Authentication router - siguiendo el patrón exacto de Autogrid
"""

from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
import secrets
import os
from datetime import datetime
from fastapi_core_database import get_db
from fastapi_core_database.security import create_access_token, get_current_user
from fastapi_core_services import EmailService
from fastapi_core_models import User, EmailVerification
from .repository import AuthRepository
from .schemas import LoginRequest, RegisterRequest, UserResponse, AuthResponse

router = APIRouter(prefix="/auth")

@router.post("/register")
def register(request: RegisterRequest, db: Session = Depends(get_db)):
    repo = AuthRepository()
    
    # Validate password requirements
    pwd_error = repo.validate_password_requirements(request.password)
    if pwd_error:
        raise HTTPException(status_code=400, detail=pwd_error)
    
    # Crear usuario con el nuevo método que verifica email y username
    user, error_message = repo.create_user(db, request.username, request.email, request.password)
    
    # Si hay un error, lanzar una excepción HTTP con el mensaje
    if error_message:
        raise HTTPException(status_code=400, detail=error_message)

    # Generate verification token (32 characters, valid for 30 minutes)
    verification_token = secrets.token_urlsafe(32)
    
    # Create email verification record
    email_verification = EmailVerification(
        user_id=user.id,
        token=verification_token,
        expires_at=EmailVerification.create_expiration(30),  # 30 minutes
        used=False
    )
    db.add(email_verification)
    db.commit()
    
    # Send verification email
    email_service = EmailService()
    frontend_url = os.getenv("FRONTEND_URL", "http://localhost:3000")
    verification_url = f"{frontend_url}/verify-email?token={verification_token}"
    
    html_body = f"""
    <html>
        <body style="font-family: Arial, sans-serif; padding: 20px; background-color: #f5f5f5;">
            <div style="max-width: 600px; margin: 0 auto; background-color: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                <h2 style="color: #333;">Welcome to R Firm SaaS, {user.username}! 🎉</h2>
                <p style="color: #666; line-height: 1.6;">Thank you for registering. Please verify your email address to activate your account.</p>
                <p style="margin: 30px 0;">
                    <a href="{verification_url}" 
                       style="background-color: #007bff; color: white; padding: 14px 28px; 
                              text-decoration: none; border-radius: 5px; display: inline-block; font-weight: bold;">
                        Verify Email Address
                    </a>
                </p>
                <p style="color: #999; font-size: 14px;">Or copy and paste this link in your browser:</p>
                <p style="color: #666; font-size: 12px; word-break: break-all; background-color: #f5f5f5; padding: 10px; border-radius: 5px;">{verification_url}</p>
                <p style="color: #999; font-size: 13px; margin-top: 30px; border-top: 1px solid #eee; padding-top: 20px;">
                    ⏱️ This link will expire in 30 minutes.<br>
                    If you didn't create this account, please ignore this email.
                </p>
                <p style="color: #666; margin-top: 20px;">Best regards,<br><strong>The R Firm Team</strong></p>
            </div>
        </body>
    </html>
    """
    
    email_sent = email_service.send_email(
        to_email=user.email,
        subject="Verify your email - R Firm SaaS",
        body=html_body,
        is_html=True
    )
    
    if not email_sent:
        # Rollback user and verification record if email fails
        db.delete(email_verification)
        db.delete(user)
        db.commit()
        raise HTTPException(
            status_code=500, 
            detail="Failed to send verification email. Please try again."
        )
    
    return {
        "message": "Registration successful! Please check your email to verify your account.",
        "email": user.email,
        "expires_in_minutes": 30
    }

@router.post("/login")
def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    """OAuth2 compatible login endpoint"""
    repo = AuthRepository()
    
    # OAuth2 uses 'username' field, but we accept username or email
    user = repo.authenticate_user(db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    if not user.email_verified:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN, 
            detail="Please verify your email address before logging in. Check your inbox."
        )
    
    if not user.is_active:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Account is inactive")
    
    token = create_access_token({"sub": user.username, "id": user.id})
    return {"access_token": token, "token_type": "bearer"}

@router.get("/me", response_model=UserResponse)
def get_me(current_user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
    repo = AuthRepository()
    user = db.query(repo.model).filter(repo.model.id == current_user["id"]).first()
    if user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return UserResponse.from_orm(user)

@router.get("/verify-email")
def verify_email(token: str, db: Session = Depends(get_db)):
    """Verify user email with token"""
    # Find verification record
    verification = db.query(EmailVerification).filter(
        EmailVerification.token == token
    ).first()
    
    if not verification:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Invalid verification token"
        )
    
    # Check if already used
    if verification.used:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="This verification link has already been used"
        )
    
    # Check if expired
    if verification.is_expired():
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Verification link has expired. Please request a new one."
        )
    
    # Get user
    user = db.query(User).filter(User.id == verification.user_id).first()
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="User not found"
        )
    
    # Mark email as verified and activate user
    user.email_verified = True
    user.is_active = True
    
    # Mark verification as used
    verification.used = True
    verification.verified_at = datetime.utcnow()
    
    db.commit()
    
    return {
        "message": "Email verified successfully! You can now log in.",
        "username": user.username,
        "email": user.email
    }

@router.post("/resend-verification")
def resend_verification(email: str, db: Session = Depends(get_db)):
    """Resend verification email"""
    # Find user by email
    user = db.query(User).filter(User.email == email).first()
    
    if not user:
        # Don't reveal if user exists or not for security
        return {
            "message": "If the email exists, a verification link has been sent."
        }
    
    # Check if already verified
    if user.email_verified:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Email is already verified"
        )
    
    # Invalidate old tokens (mark as used)
    old_verifications = db.query(EmailVerification).filter(
        EmailVerification.user_id == user.id,
        EmailVerification.used == False
    ).all()
    
    for old_ver in old_verifications:
        old_ver.used = True
    
    # Generate new verification token
    verification_token = secrets.token_urlsafe(32)
    
    # Create new email verification record
    email_verification = EmailVerification(
        user_id=user.id,
        token=verification_token,
        expires_at=EmailVerification.create_expiration(30),
        used=False
    )
    db.add(email_verification)
    db.commit()
    
    # Send verification email
    email_service = EmailService()
    frontend_url = os.getenv("FRONTEND_URL", "http://localhost:3000")
    verification_url = f"{frontend_url}/verify-email?token={verification_token}"
    
    html_body = f"""
    <html>
        <body style="font-family: Arial, sans-serif; padding: 20px; background-color: #f5f5f5;">
            <div style="max-width: 600px; margin: 0 auto; background-color: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                <h2 style="color: #333;">Email Verification - R Firm SaaS</h2>
                <p style="color: #666; line-height: 1.6;">You requested a new verification link. Click the button below to verify your email address.</p>
                <p style="margin: 30px 0;">
                    <a href="{verification_url}" 
                       style="background-color: #007bff; color: white; padding: 14px 28px; 
                              text-decoration: none; border-radius: 5px; display: inline-block; font-weight: bold;">
                        Verify Email Address
                    </a>
                </p>
                <p style="color: #999; font-size: 14px;">Or copy and paste this link in your browser:</p>
                <p style="color: #666; font-size: 12px; word-break: break-all; background-color: #f5f5f5; padding: 10px; border-radius: 5px;">{verification_url}</p>
                <p style="color: #999; font-size: 13px; margin-top: 30px; border-top: 1px solid #eee; padding-top: 20px;">
                    ⏱️ This link will expire in 30 minutes.<br>
                    If you didn't request this, please ignore this email.
                </p>
                <p style="color: #666; margin-top: 20px;">Best regards,<br><strong>The R Firm Team</strong></p>
            </div>
        </body>
    </html>
    """
    
    email_service.send_email(
        to_email=user.email,
        subject="Verify your email - R Firm SaaS",
        body=html_body,
        is_html=True
    )
    
    return {
        "message": "If the email exists, a verification link has been sent.",
        "expires_in_minutes": 30
    }

@router.post("/refresh")
def refresh_token(current_user: dict = Depends(get_current_user)):
    """Refresh access token"""
    token = create_access_token({"sub": current_user["username"], "id": current_user["id"]})
    return {"access_token": token, "token_type": "bearer"}
