from typing import Optional

from fastapi import APIRouter, Depends, Query, HTTPException
from sqlalchemy.orm import Session

from core.database import get_core_db
from core.security import get_current_user, validate_access_to_resource
from .dtos import (
    ConceptManifestationCreateDTO,
    ConceptManifestationUpdateDTO,
    ConceptManifestationResponseDTO,
    ConceptManifestationListDTO,
)
from .service import ConceptManifestationService

router = APIRouter(prefix="/concept-manifestations")


@router.get("/", response_model=ConceptManifestationListDTO)
async def list_concept_manifestations(
    company_id: int = Query(..., description="Company ID"),
    value_manifestation_id: Optional[int] = Query(
        None, description="Filter by Value Manifestation ID"
    ),
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    filters = {}
    if value_manifestation_id:
        filters["value_manifestation_id"] = value_manifestation_id

    items, total = ConceptManifestationService.get_all(
        db, tenant_id, company_id, skip=skip, limit=limit, filters=filters
    )
    return {
        "items": [ConceptManifestationResponseDTO.model_validate(item) for item in items],
        "total": total,
        "page": (skip // limit) + 1,
        "page_size": limit,
    }


@router.post("/", response_model=ConceptManifestationResponseDTO)
async def create_concept_manifestation(
    data: ConceptManifestationCreateDTO,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    return ConceptManifestationService.create(db, data, tenant_id, company_id)


@router.get(
    "/{value_manifestation_id}/{line_number}",
    response_model=ConceptManifestationResponseDTO,
)
async def get_concept_manifestation(
    value_manifestation_id: int,
    line_number: int,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    item = ConceptManifestationService.get_by_id(
        db, value_manifestation_id, line_number, tenant_id, company_id
    )
    if not item:
        raise HTTPException(status_code=404, detail="Concept Manifestation not found")
    return item


@router.patch(
    "/{value_manifestation_id}/{line_number}",
    response_model=ConceptManifestationResponseDTO,
)
async def update_concept_manifestation(
    value_manifestation_id: int,
    line_number: int,
    data: ConceptManifestationUpdateDTO,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    item = ConceptManifestationService.update(
        db, value_manifestation_id, line_number, tenant_id, company_id, data
    )
    if not item:
        raise HTTPException(status_code=404, detail="Concept Manifestation not found")
    return item


@router.delete("/{value_manifestation_id}/{line_number}", response_model=bool)
async def delete_concept_manifestation(
    value_manifestation_id: int,
    line_number: int,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    success = ConceptManifestationService.delete(
        db, value_manifestation_id, line_number, tenant_id, company_id
    )
    if not success:
        raise HTTPException(status_code=404, detail="Concept Manifestation not found")
    return success
