from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List

from database import get_db
from models.global_settings import GlobalSettings
from schemas.global_settings import (
    GlobalSetting, 
    GlobalSettingCreate, 
    GlobalSettingUpdate,
    UploadLimitResponse,
    UploadLimitUpdate
)
from utils.auth import get_current_user, require_admin_permission
from models.user import User

router = APIRouter(prefix="/settings", tags=["settings"])

# Default upload limit in MB (1GB)
DEFAULT_UPLOAD_LIMIT_MB = 1000
UPLOAD_LIMIT_KEY = "global_upload_limit_mb"


def get_or_create_upload_limit_setting(db: Session) -> GlobalSettings:
    """Get or create the upload limit setting with default value"""
    setting = db.query(GlobalSettings).filter(
        GlobalSettings.setting_key == UPLOAD_LIMIT_KEY
    ).first()
    
    if not setting:
        setting = GlobalSettings(
            setting_key=UPLOAD_LIMIT_KEY,
            setting_value=str(DEFAULT_UPLOAD_LIMIT_MB),
            description="Global upload size limit for movie files in MB"
        )
        db.add(setting)
        db.commit()
        db.refresh(setting)
    
    return setting


@router.get("/upload-limit", response_model=UploadLimitResponse)
async def get_upload_limit(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """Get the global upload size limit for movie files"""
    setting = get_or_create_upload_limit_setting(db)
    
    return UploadLimitResponse(
        upload_limit_mb=int(setting.setting_value),
        description=setting.description or "Global upload size limit for movie files"
    )


@router.put("/upload-limit", response_model=UploadLimitResponse)
async def update_upload_limit(
    upload_limit: UploadLimitUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_admin_permission)
):
    """Update the global upload size limit for movie files (admin only)"""
    setting = get_or_create_upload_limit_setting(db)
    
    setting.setting_value = str(upload_limit.upload_limit_mb)
    db.commit()
    db.refresh(setting)
    
    return UploadLimitResponse(
        upload_limit_mb=int(setting.setting_value),
        description=setting.description or "Global upload size limit for movie files"
    )


@router.get("/", response_model=List[GlobalSetting])
async def get_all_settings(
    db: Session = Depends(get_db),
    current_user: User = Depends(require_admin_permission)
):
    """Get all global settings (admin only)"""
    settings = db.query(GlobalSettings).all()
    return settings


@router.post("/", response_model=GlobalSetting)
async def create_setting(
    setting: GlobalSettingCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_admin_permission)
):
    """Create a new global setting (admin only)"""
    # Check if setting already exists
    existing = db.query(GlobalSettings).filter(
        GlobalSettings.setting_key == setting.setting_key
    ).first()
    
    if existing:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Setting with key '{setting.setting_key}' already exists"
        )
    
    db_setting = GlobalSettings(**setting.dict())
    db.add(db_setting)
    db.commit()
    db.refresh(db_setting)
    
    return db_setting


@router.put("/{setting_key}", response_model=GlobalSetting)
async def update_setting(
    setting_key: str,
    setting_update: GlobalSettingUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_admin_permission)
):
    """Update a specific global setting (admin only)"""
    setting = db.query(GlobalSettings).filter(
        GlobalSettings.setting_key == setting_key
    ).first()
    
    if not setting:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Setting with key '{setting_key}' not found"
        )
    
    for field, value in setting_update.dict(exclude_unset=True).items():
        setattr(setting, field, value)
    
    db.commit()
    db.refresh(setting)
    
    return setting


@router.delete("/{setting_key}")
async def delete_setting(
    setting_key: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_admin_permission)
):
    """Delete a global setting (admin only)"""
    setting = db.query(GlobalSettings).filter(
        GlobalSettings.setting_key == setting_key
    ).first()
    
    if not setting:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Setting with key '{setting_key}' not found"
        )
    
    # Prevent deletion of critical settings
    if setting_key == UPLOAD_LIMIT_KEY:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Cannot delete the global upload limit setting"
        )
    
    db.delete(setting)
    db.commit()
    
    return {"message": f"Setting '{setting_key}' deleted successfully"}