from typing import List, Optional
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
from .service import HistoricalTariffFractionService
from .schemas import HistoricalTariffFractionResponse, HistoricalTariffFractionCreate, HistoricalTariffFractionUpdate, HistoricalTariffFractionListResponse

from api.v1.common.tenant_crud_routes import validate_access_to_resource

router = APIRouter()

@router.get("/", response_model=HistoricalTariffFractionListResponse)
def get_historical_fractions(
    company_id: int = Query(..., description="Company ID"),
    page: int = Query(1, ge=1, description="Page number"),
    page_size: int = Query(50, ge=1, le=1000, description="Page size"),
    historical_fraction: Optional[str] = Query(None, description="Search by historical fraction code"),
    db: Session = Depends(get_core_db),
    current_user = Depends(get_current_user)
):
    """
    Get all historical tariff fractions (paginated).
    """
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    skip = (page - 1) * page_size
    service = HistoricalTariffFractionService(db)
    items, total = service.get_multi(tenant_id, company_id, skip=skip, limit=page_size, historical_fraction=historical_fraction)
    return {
        "items": items,
        "total": total,
        "page": page,
        "page_size": page_size,
        "pages": (total + page_size - 1) // page_size if page_size > 0 else 1
    }

@router.get("/{id}", response_model=HistoricalTariffFractionResponse)
def get_historical_fraction(
    id: int,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user = Depends(get_current_user)
):
    """
    Get a historical tariff fraction by ID.
    """
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    service = HistoricalTariffFractionService(db)
    fraction = service.get(id, tenant_id, company_id)
    if not fraction:
        raise HTTPException(status_code=404, detail="Historical tariff fraction not found")
    return fraction

@router.post("/", response_model=HistoricalTariffFractionResponse)
def create_historical_fraction(
    fraction_in: HistoricalTariffFractionCreate,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user = Depends(get_current_user)
):
    """
    Create a new historical tariff fraction.
    """
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    service = HistoricalTariffFractionService(db)
    return service.create(fraction_in, tenant_id, company_id)

@router.put("/{id}", response_model=HistoricalTariffFractionResponse)
def update_historical_fraction(
    id: int,
    fraction_in: HistoricalTariffFractionUpdate,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user = Depends(get_current_user)
):
    """
    Update a historical tariff fraction.
    """
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    service = HistoricalTariffFractionService(db)
    fraction = service.get(id, tenant_id, company_id)
    if not fraction:
        raise HTTPException(status_code=404, detail="Historical tariff fraction not found")
    return service.update(fraction, fraction_in)

@router.delete("/{id}", response_model=HistoricalTariffFractionResponse)
def delete_historical_fraction(
    id: int,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user = Depends(get_current_user)
):
    """
    Delete a historical tariff fraction.
    """
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    service = HistoricalTariffFractionService(db)
    fraction = service.get(id, tenant_id, company_id)
    if not fraction:
        raise HTTPException(status_code=404, detail="Historical tariff fraction not found")
    return service.delete(id, tenant_id, company_id)
