from datetime import date
from typing import Optional, Literal

from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession

from app.database.session import get_db
from app.domain.entities.lens_issues import LensIssueEntity
from app.domain.entities.responses.paginated_issue import PaginatedLensIssuesResponseEntity
from app.infrastructure.dependencies import get_current_user
from app.infrastructure.lens_issues_service import LensIssuesService

router = APIRouter()


@router.get(
    "/",
    response_model=PaginatedLensIssuesResponseEntity,
    summary="Get all lens issues",
    description="Returns a paginated list of lens issues with optional filtering and sorting",
)
async def get_all_lens_issues(
    page: int = Query(1, ge=1),
    page_size: int = Query(10, ge=1, le=100),
    search: Optional[str] = Query(None),
    sort_order: Literal["asc", "desc"] = Query("desc"),
    start_date: Optional[date] = Query(None),
    end_date: Optional[date] = Query(None),
    db: AsyncSession = Depends(get_db),
    user=Depends(get_current_user),
):
    lens_issues_service = LensIssuesService(db)
    skip = (page - 1) * page_size
    issues, total_count = await lens_issues_service.get_all_lens_issues(
        skip=skip,
        limit=page_size,
        search=search,
        sort_order=sort_order,
        start_date=start_date,
        end_date=end_date
    )
    return PaginatedLensIssuesResponseEntity(
        issues=issues,
        total_count=total_count
    )

@router.post(
    "/",
    response_model=LensIssueEntity,
    summary="Create lens issue",
    description="Creates a new lens issue",
)
async def create_lens_issue(
        lens_issue: LensIssueEntity,
        db: AsyncSession = Depends(get_db),
        user=Depends(get_current_user),
):
    lens_issues_service = LensIssuesService(db)
    return await lens_issues_service.create_lens_issue(lens_issue, user.id)
