"""
Authentication Routes - Login and JWT token management.
"""

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
import structlog

from app.core.auth import jwt_auth
from app.db.postgres import db

logger = structlog.get_logger(__name__)

router = APIRouter()


class LoginRequest(BaseModel):
    """Login request."""
    license_key: str
    email: str


class LoginResponse(BaseModel):
    """Login response."""
    token: str
    refresh_token: str
    tier: str
    email: str
    expires_at: str


@router.post("/login", response_model=LoginResponse)
async def login(request: LoginRequest):
    """
    Login with license key and email.
    
    Returns JWT token for authenticated requests.
    """
    logger.info("login_attempt", email=request.email)
    
    # Verify license exists and matches email
    license_row = await db.fetchrow(
        """
        SELECT license_key, email, tier, expires_at, status
        FROM licenses
        WHERE license_key = $1 AND email = $2
        """,
        request.license_key,
        request.email
    )
    
    if not license_row:
        # Check team members
        license_row = await db.fetchrow(
            """
            SELECT tm.license_key, tm.email, l.tier, l.expires_at, l.status
            FROM team_members tm
            JOIN licenses l ON tm.license_key = l.license_key
            WHERE tm.license_key = $1 AND tm.email = $2
            """,
            request.license_key,
            request.email
        )
        
    if not license_row:
        logger.warning("login_failed_invalid_credentials", email=request.email)
        raise HTTPException(
            status_code=401,
            detail="Invalid license key or email"
        )
    
    # Check license status
    if license_row['status'] != 'active':
        logger.warning("login_failed_inactive_license",
                      email=request.email,
                      status=license_row['status'])
        raise HTTPException(
            status_code=403,
            detail=f"License is {license_row['status']}"
        )
    
    # Create JWT token
    token = jwt_auth.create_token(
        license_key=request.license_key,
        email=request.email,
        tier=license_row['tier']
    )
    
    # Create refresh token
    refresh_token = jwt_auth.create_refresh_token(
        license_key=request.license_key,
        email=request.email
    )
    
    logger.info("login_successful", email=request.email, tier=license_row['tier'])
    
    # Send welcome email for new users (check if first login)
    try:
        from app.utils.email import email_service
        # Only send if this is their first login (you could track this in the DB)
        await email_service.send_welcome_email(request.email, request.email.split('@')[0])
    except Exception as e:
        logger.error("welcome_email_failed", error=str(e))
    
    return LoginResponse(
        token=token,
        refresh_token=refresh_token,
        tier=license_row['tier'],
        email=request.email,
        expires_at=str(license_row['expires_at']) if license_row['expires_at'] else 'Never'
    )


class RefreshRequest(BaseModel):
    refresh_token: str


@router.post("/refresh", response_model=LoginResponse)
async def refresh_token(request: RefreshRequest):
    """Refresh access token."""
    payload = jwt_auth.verify_token(request.refresh_token)
    
    if not payload or payload.get('type') != 'refresh':
        raise HTTPException(status_code=401, detail="Invalid refresh token")
        
    # Verify user still exists/active
    license_row = await db.fetchrow(
        "SELECT tier, expires_at, status FROM licenses WHERE license_key = $1",
        payload['sub']
    )
    
    if not license_row or license_row['status'] != 'active':
        raise HTTPException(status_code=401, detail="License inactive")
        
    # Create new tokens
    new_token = jwt_auth.create_token(
        license_key=payload['sub'],
        email=payload['email'],
        tier=license_row['tier']
    )
    
    return LoginResponse(
        token=new_token,
        refresh_token=request.refresh_token, # Return same refresh token (rotation could be added later)
        tier=license_row['tier'],
        email=payload['email'],
        expires_at=str(license_row['expires_at']) if license_row['expires_at'] else 'Never'
    )
