from fastapi import APIRouter, Depends, Query, status
from sqlalchemy.orm import Session
from src.core.dependencies import get_db
from src.apps.wine_settings.schemas.appellations import (
    WineAppellationOutSchema,
    WineAppellationCreateSchema,
    WineAppellationUpdateSchema,
)
from src.apps.wine_settings.services import appellations as service
from src.apps.base.schemas.response_model import ResponseModel
from src.utils import constants

router = APIRouter(prefix="/wine-appellations", tags=["Wine Appellations"])


@router.get("/", response_model=ResponseModel, summary="Get all wine appellations with pagination")
def get_all_wine_appellations(
    page: int = Query(default=1, ge=1, description="Page number to fetch"),
    per_page: int = Query(
        default=constants.DEFAULT_PER_PAGE,
        ge=1,
        le=constants.MAX_PER_PAGE,
        description="Number of items per page"
    ),
    db: Session = Depends(get_db),
):
    data = service.get_all_wine_appellations(db=db, page=page, per_page=per_page)
    return ResponseModel(
        data=data,
        status_code=200,
        success=True,
        message="Wine appellations fetched successfully",
    )


@router.get("/{appellation_id}", response_model=ResponseModel, summary="Get wine appellation by ID")
def get_appellation(appellation_id: int, db: Session = Depends(get_db)):
    appellation = service.get_wine_appellation_by_id(db, appellation_id)
    return ResponseModel(
        data=WineAppellationOutSchema.from_orm(appellation),
        status_code=200,
        success=True,
        message="Wine appellation fetched successfully",
    )


@router.post("/", response_model=ResponseModel, status_code=status.HTTP_201_CREATED, summary="Create wine appellation")
def create_appellation(payload: WineAppellationCreateSchema, db: Session = Depends(get_db)):
    created = service.create_wine_appellation(db, payload)
    return ResponseModel(
        data=WineAppellationOutSchema.from_orm(created),
        status_code=201,
        success=True,
        message="Wine appellation created successfully",
    )


@router.put("/{appellation_id}", response_model=ResponseModel, summary="Update wine appellation")
def update_appellation(
    appellation_id: int, payload: WineAppellationUpdateSchema, db: Session = Depends(get_db)
):
    updated = service.update_wine_appellation(db, appellation_id, payload)
    return ResponseModel(
        data=WineAppellationOutSchema.from_orm(updated),
        status_code=200,
        success=True,
        message="Wine appellation updated successfully",
    )


@router.delete("/{appellation_id}", response_model=ResponseModel, summary="Delete wine appellation")
def delete_appellation(appellation_id: int, db: Session = Depends(get_db)):
    service.delete_wine_appellation(db, appellation_id)
    return ResponseModel(
        data={},
        status_code=200,
        success=True,
        message="Wine appellation deleted successfully",
    )
