from typing import List, Optional
from sqlalchemy.orm import Session
from .models import ItemPreset
from .dto import ItemPresetCreate, ItemPresetUpdate

def get_presets(db: Session, tenant_id: int, company_id: int) -> List[ItemPreset]:
    """Get all presets for a specific company and tenant"""
    return db.query(ItemPreset).filter(
        ItemPreset.tenant_id == tenant_id,
        ItemPreset.company_id == company_id
    ).all()

def get_preset_by_id(db: Session, preset_id: int, tenant_id: int, company_id: int) -> Optional[ItemPreset]:
    """Get a specific preset by ID"""
    return db.query(ItemPreset).filter(
        ItemPreset.id == preset_id,
        ItemPreset.tenant_id == tenant_id,
        ItemPreset.company_id == company_id
    ).first()

def create_preset(db: Session, tenant_id: int, company_id: int, data: ItemPresetCreate) -> ItemPreset:
    """Create a new item preset"""
    new_preset = ItemPreset(
        tenant_id=tenant_id,
        company_id=company_id,
        name=data.name,
        description=data.description,
        items=data.items
    )
    db.add(new_preset)
    db.commit()
    db.refresh(new_preset)
    return new_preset

def update_preset(
    db: Session, 
    preset_id: int, 
    tenant_id: int, 
    company_id: int, 
    data: ItemPresetUpdate
) -> Optional[ItemPreset]:
    """Update an existing item preset"""
    preset = get_preset_by_id(db, preset_id, tenant_id, company_id)
    if not preset:
        return None
    
    update_data = data.model_dump(exclude_unset=True)
    for key, value in update_data.items():
        setattr(preset, key, value)
    
    db.commit()
    db.refresh(preset)
    return preset

def delete_preset(db: Session, preset_id: int, tenant_id: int, company_id: int) -> bool:
    """Delete an item preset"""
    preset = get_preset_by_id(db, preset_id, tenant_id, company_id)
    if not preset:
        return False
    
    db.delete(preset)
    db.commit()
    return True
