from fastapi import APIRouter, Depends, Query, status
from sqlalchemy.orm import Session
from typing import Optional
from utils.utils import get_db
from . import handler
from .schema import (
    InsuranceproviderCreate,
    InsuranceproviderUpdate,
    InsuranceproviderResponse,
    InsuranceproviderListResponse,
)

router = APIRouter(prefix="/insurance-providers", tags=["Insurance Providers"])


@router.post(
    "/",
    response_model=InsuranceproviderResponse,
    status_code=status.HTTP_201_CREATED,
    summary="Create Insurance Provider",
    description="Creates a new insurance provider record. Returns 409 if an insurance provider with the same name already exists.",
)
def create_insuranceprovider_route(data: InsuranceproviderCreate, db: Session = Depends(get_db)):
    return handler.create_insuranceprovider(db, data)


@router.get(
    "/",
    response_model=InsuranceproviderListResponse,
    summary="List Insurance Providers",
    description="Returns a paginated list of insurance providers. Supports optional search filter on name, contact person, and email fields.",
)
def list_insuranceproviders_route(
    limit: int = Query(20, ge=1),
    offset: int = Query(0, ge=0),
    search: Optional[str] = None,
    db: Session = Depends(get_db),
):
    return handler.list_insuranceproviders(db, limit, offset, search=search)


@router.get(
    "/{entity_id}",
    response_model=InsuranceproviderResponse,
    summary="Get Insurance Provider by ID",
    description="Returns details of a single insurance provider by ID. Returns 404 if the insurance provider does not exist.",
)
def get_insuranceprovider_route(entity_id: str, db: Session = Depends(get_db)):
    return handler.get_insuranceprovider_by_id(db, entity_id)


@router.put(
    "/{entity_id}",
    response_model=InsuranceproviderResponse,
    summary="Update Insurance Provider",
    description="Updates an existing insurance provider record. Returns 404 if the insurance provider does not exist. Returns 409 if the updated name conflicts with another provider.",
)
def update_insuranceprovider_route(
    entity_id: str, data: InsuranceproviderUpdate, db: Session = Depends(get_db)
):
    return handler.update_insuranceprovider(db, entity_id, data)


@router.delete(
    "/{entity_id}",
    status_code=status.HTTP_200_OK,
    summary="Delete Insurance Provider",
    description="Deletes an insurance provider record. Returns 404 if the insurance provider does not exist. Returns 409 if the provider is referenced by existing patients.",
)
def delete_insuranceprovider_route(entity_id: str, db: Session = Depends(get_db)):
    return handler.delete_insuranceprovider(db, entity_id)