from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List, Dict, Any

from core.database import get_core_db
from core.security import get_current_user, validate_access_to_resource
from api.v1.common.tenant_crud_routes import TenantCRUDRoutes
from . import service
from .models import Equivalency, EquivalencyItem
from .dto import (
    EquivalencyCreate, EquivalencyResponse, EquivalencyUpdate,
    EquivalencyItemCreate, EquivalencyItemResponse, EquivalencyItemUpdate
)
from .service import EquivalencyService, EquivalencyItemService

router = APIRouter(prefix="/equivalencies",
                   tags=["a76.general_catalogs.equivalencies"])

# Equivalency CRUD
equivalency_crud = TenantCRUDRoutes(
    service=EquivalencyService,
    create_schema=EquivalencyCreate,
    update_schema=EquivalencyUpdate,
    response_schema=EquivalencyResponse,
    prefix="",
    tags=["Equivalencies"],
    resource_name="Equivalency",
    enable_list=True,
)

# Equivalency Item CRUD
item_crud = TenantCRUDRoutes(
    service=EquivalencyItemService,
    create_schema=EquivalencyItemCreate,
    update_schema=EquivalencyItemUpdate,
    response_schema=EquivalencyItemResponse,
    prefix="/items",
    tags=["Equivalency Items"],
    resource_name="EquivalencyItem",
    enable_list=True,
)

# Custom endpoint for creating items nested under equivalency


@equivalency_crud.router.post(
    "/{equivalency_id}/items",
    response_model=EquivalencyItemResponse,
    status_code=status.HTTP_201_CREATED,
    summary="Create equivalency item",
)
async def create_equivalency_item(
    equivalency_id: int,
    data: EquivalencyItemCreate,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    tenant_id = validate_access_to_resource(db, company_id, current_user)

    # Verify parent exists
    parent = EquivalencyService.get_by_id(
        db, equivalency_id, tenant_id, company_id)
    if not parent:
        raise HTTPException(status_code=404, detail="Equivalency not found")

    # Create item
    # We need to manually handle the creation because the DTO doesn't have equivalency_id
    # and the service.create expects data to match the model or DTO.
    # But service.create takes EquivalencyItemCreate which doesn't have equivalency_id.
    # So we need to modify the data or handle it in service.

    # Actually, I implemented EquivalencyItemService.create to take EquivalencyItemCreate.
    # And it tries to create the model.
    # But the model needs equivalency_id.
    # So EquivalencyItemService.create will fail if I don't pass equivalency_id.
    # I should update EquivalencyItemService.create to accept extra kwargs or handle this.

    # Let's update the service call here to pass equivalency_id manually if I can't change the service signature easily.
    # But wait, I can just instantiate the model here or update the service.

    # I'll update the service to handle it.
    # But for now, let's assume I can pass it in the data if I convert it to dict.

    item_data = data.model_dump()
    item_data['equivalency_id'] = equivalency_id

    # I need to call a method that accepts this.
    # EquivalencyItemService.create takes EquivalencyItemCreate.
    # I should probably add a specific method for this or update create.

    # Let's use a direct DB call here or add a method to service.
    # Adding a method to service is cleaner.

    return EquivalencyItemService.create_nested(db, equivalency_id, data, tenant_id, company_id)


router.include_router(equivalency_crud.router)
router.include_router(item_crud.router)
