from fastapi import APIRouter, Depends, Query, HTTPException
from sqlalchemy.orm import Session
from typing import Optional, Dict, Any
from core.database import get_core_db
from .service import AppSettingsService
from .schemas import AppSettingRequest, AppSettingResponse
from core.security import get_current_user, validate_access_to_resource

router = APIRouter(prefix="/a76/app-settings", tags=["a76 / app_settings"])

import logging
import traceback

logger = logging.getLogger(__name__)

@router.get("/resolved")
def get_resolved_settings(
    tenant_id: int = Query(...),
    company_id: int = Query(...),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user)
):
    """
    Returns the final merged configuration for a company.
    Merges Global -> Tenant -> Company levels.
    """
    try:
        # Validar permisos
        validate_access_to_resource(db, company_id, current_user, ["settings_general.view"])
        
        return AppSettingsService.get_resolved_settings(db, tenant_id, company_id)
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"RESOLVE ERROR: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/upsert")
def upsert_settings(
    payload: AppSettingRequest,
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user)
):
    """
    Creates or updates an override for a specific level (Global, Tenant, or Company).
    """
    try:
        # Validar permisos
        validate_access_to_resource(db, payload.company_id, current_user, ["settings_general.edit"])
        
        data = payload.settings.model_dump(exclude_unset=True)
        return AppSettingsService.upsert_settings(
            db, 
            payload.tenant_id, 
            payload.company_id, 
            data
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"UPSERT ERROR: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/upsert")
def update_settings(
    payload: AppSettingRequest,
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user)
):
    """
    Alias for upsert_settings.
    """
    return upsert_settings(payload, db, current_user)
