from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPBearer
from sqlalchemy.orm import Session
from pydantic import BaseModel
from typing import List, Optional
import os

from ..models.database import get_db, APIKey
from ..auth.middleware import auth_middleware

router = APIRouter(prefix="/api/auth", tags=["authentication"])

# Request/Response models
class LoginRequest(BaseModel):
    secret_key: str

class LoginResponse(BaseModel):
    token: str

class APIKeyCreate(BaseModel):
    description: str

class APIKeyResponse(BaseModel):
    id: int
    key: str
    description: Optional[str]
    created_at: str

    class Config:
        from_attributes = True

class APIKeyList(BaseModel):
    keys: List[APIKeyResponse]

# Get admin secret key
def get_admin_secret_key():
    return os.getenv("ADMIN_SECRET_KEY", "admin-secret-key-change-in-production")

@router.post("/login", response_model=LoginResponse)
async def login(request: LoginRequest):
    """Admin login"""
    admin_key = get_admin_secret_key()
    
    if request.secret_key != admin_key:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid secret key"
        )
    
    # Generate JWT token
    token = auth_middleware.create_access_token(
        data={"sub": "admin", "role": "admin"}
    )
    
    return LoginResponse(token=token)

@router.post("/keys", response_model=APIKeyResponse)
async def create_api_key(
    request: APIKeyCreate,
    db: Session = Depends(get_db),
    current_user: dict = Depends(auth_middleware.get_current_user)
):
    """Create a new API key"""
    # Generate new API key
    api_key_value = auth_middleware.generate_api_key()
    
    # Save to database
    db_key = APIKey(
        key=api_key_value,
        description=request.description
    )
    
    db.add(db_key)
    db.commit()
    db.refresh(db_key)
    
    return APIKeyResponse(
        id=db_key.id,
        key=db_key.key,
        description=db_key.description,
        created_at=db_key.created_at.isoformat()
    )

@router.get("/keys", response_model=APIKeyList)
async def list_api_keys(
    db: Session = Depends(get_db),
    current_user: dict = Depends(auth_middleware.get_current_user)
):
    """Get all API keys"""
    keys = db.query(APIKey).order_by(APIKey.created_at.desc()).all()
    
    return APIKeyList(
        keys=[
            APIKeyResponse(
                id=key.id,
                key=key.key,
                description=key.description,
                created_at=key.created_at.isoformat()
            )
            for key in keys
        ]
    )

@router.delete("/keys/{key_id}")
async def delete_api_key(
    key_id: int,
    db: Session = Depends(get_db),
    current_user: dict = Depends(auth_middleware.get_current_user)
):
    """Delete API key"""
    key = db.query(APIKey).filter(APIKey.id == key_id).first()
    
    if not key:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="API key not found"
        )
    
    db.delete(key)
    db.commit()
    
    return {"message": "API key deleted successfully"} 