""" CRUD operations for availability rules """
from typing import List, Optional
from uuid import UUID
from sqlmodel import Session, select, func
from fastapi import HTTPException

from app.models import (
    AvailabilityRule,
    AvailabilityRuleCreate,
    AvailabilityRuleUpdate,
    AvailabilityRuleOut,
    Service
)

def create_availability_rule(
    *,
    session: Session,
    obj_in: AvailabilityRuleCreate,
    service_id: UUID
) -> AvailabilityRuleOut:
    """Create a new availability rule"""
    # Verify that the service exists
    service = session.get(Service, service_id)
    if not service:
        raise HTTPException(status_code=404, detail="Service not found")
    
    # Create the rule
    db_obj = AvailabilityRule(
        service_id=service_id,
        dias_semana=obj_in.dias_semana,
        hora_inicio=obj_in.hora_inicio,
        hora_fin=obj_in.hora_fin,
        price=obj_in.price,
        min_days_before=obj_in.min_days_before
    )
    session.add(db_obj)
    session.commit()
    session.refresh(db_obj)
    
    return db_obj

def get_availability_rule(
    *,
    session: Session,
    rule_id: UUID
) -> Optional[AvailabilityRuleOut]:
    """Get an availability rule by ID"""
    return session.get(AvailabilityRule, rule_id)

def get_availability_rules_by_service(
    *,
    session: Session,
    service_id: UUID,
    skip: int = 0,
    limit: int = 100
) -> List[AvailabilityRuleOut]:
    """Get all availability rules for a service"""
    statement = select(AvailabilityRule).where(
        AvailabilityRule.service_id == service_id
    ).offset(skip).limit(limit)
    
    return session.exec(statement).all()

def update_availability_rule(
    *,
    session: Session,
    rule_id: UUID,
    obj_in: AvailabilityRuleUpdate
) -> Optional[AvailabilityRuleOut]:
    """Update an availability rule"""
    db_obj = session.get(AvailabilityRule, rule_id)
    if not db_obj:
        return None
    
    update_data = obj_in.model_dump(exclude_unset=True)
    for field, value in update_data.items():
        setattr(db_obj, field, value)
    
    session.add(db_obj)
    session.commit()
    session.refresh(db_obj)
    
    return db_obj

def delete_availability_rule(
    *,
    session: Session,
    rule_id: UUID
) -> None:
    """Delete an availability rule"""
    db_obj = session.get(AvailabilityRule, rule_id)
    if not db_obj:
        raise HTTPException(status_code=404, detail="Availability rule not found")
    
    session.delete(db_obj)
    session.commit() 