from typing import List, Dict, Any
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from core.database import get_core_db
from core.security import get_current_user, validate_access_to_resource
from api.v1.modules.a76.invoice_settings import services
from api.v1.modules.a76.invoice_settings.dto import InvoiceSettingsRequest, InvoiceSettingsResponse, OperationType

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

@router.get("/{invoice_type}", response_model=InvoiceSettingsResponse)
def get_invoice_settings(
    invoice_type: str,
    operation_type: OperationType = Query(...),
    company_id: int = Query(...),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """Get settings for a specific invoice type and operation"""
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    
    settings = services.get_settings(
        db,
        tenant_id,
        company_id,
        invoice_type,
        operation_type
    )
    
    if not settings:
        # Return empty default if not found, to simplify frontend logic
        return InvoiceSettingsResponse(
            invoice_type=invoice_type,
            operation_type=operation_type,
            settings={},
            id=0,
            tenant_id=tenant_id,
            company_id=company_id
        )
    return InvoiceSettingsResponse.model_validate(settings)

@router.get("/", response_model=List[InvoiceSettingsResponse])
def list_invoice_settings(
    company_id: int = Query(...),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """List all configured settings for validation or overview"""
    tenant_id = validate_access_to_resource(db, company_id, current_user)

    return services.list_settings(
        db,
        tenant_id,
        company_id
    )

@router.put("/", response_model=InvoiceSettingsResponse)
def save_invoice_settings(
    settings_data: InvoiceSettingsRequest,
    company_id: int = Query(...),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """Create or update invoice settings"""
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    
    return services.upsert_settings(
        db,
        tenant_id,
        company_id,
        settings_data
    )
