from typing import Any, Dict, 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, validate_access_to_resource

from .dto import DocumentTypeDigitizationResponse
from .service import DocumentTypeDigitizationService

router = APIRouter(prefix='/document-types-digitization', tags=['Document Types Digitization'])
VIEW_PERMISSION = ['ref_invoice_types.view']


@router.get('/', response_model=Dict[str, Any])
async def list_document_types(
	company_id: int = Query(..., description='Company ID'),
	page: int = Query(1, ge=1, description='Page number'),
	page_size: int = Query(50, ge=1, le=2000, description='Page size'),
	search: Optional[str] = Query(None, description='Search by code or description'),
	active_only: bool = Query(False, description='Only active records'),
	sort_by: Optional[str] = Query('code', description='Column to sort by'),
	sort_order: str = Query('asc', pattern='^(asc|desc)$', description='Sort order'),
	db: Session = Depends(get_core_db),
	current_user: dict = Depends(get_current_user),
):
	tenant_id = validate_access_to_resource(db, company_id, current_user, VIEW_PERMISSION)
	skip = (page - 1) * page_size
	filters: Dict[str, Any] = {}

	if search:
		filters['search'] = search
	if active_only:
		filters['active_only'] = True

	items, total = DocumentTypeDigitizationService.get_all(
		db,
		tenant_id,
		company_id,
		skip,
		page_size,
		filters,
		sort_by,
		sort_order,
	)

	return {
		'items': [DocumentTypeDigitizationResponse.model_validate(item) for item in items],
		'total': total,
		'page': page,
		'page_size': page_size,
	}


@router.get('/{document_type_id}/', response_model=DocumentTypeDigitizationResponse)
async def get_document_type(
	document_type_id: 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, VIEW_PERMISSION)
	document_type = DocumentTypeDigitizationService.get_by_id(
		db,
		document_type_id,
		tenant_id,
		company_id,
	)

	if not document_type:
		raise HTTPException(
			status_code=404,
			detail=f'Tipo de documento con ID {document_type_id} no encontrado',
		)

	return document_type


@router.get('/by-code/{code}/', response_model=DocumentTypeDigitizationResponse)
async def get_document_type_by_code(
	code: str,
	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, VIEW_PERMISSION)
	document_type = DocumentTypeDigitizationService.get_by_code(
		db,
		code,
		tenant_id,
		company_id,
	)

	if not document_type:
		raise HTTPException(status_code=404, detail=f'Tipo de documento con codigo {code} no encontrado')

	return document_type
