from typing import List

from core.database import get_core_db
from core.security import get_current_user
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from .dto import CountryRuleOctCreateDTO, CountryRuleOctResponseDTO
from .services import CountryRuleOctService

router = APIRouter(prefix="/country-rule-oct")


@router.get("/", response_model=List[CountryRuleOctResponseDTO])
async def list_countries(
    db: Session = Depends(get_core_db), current_user: dict = Depends(get_current_user)
):
    """
    List all CountryRuleOct entries.
    """
    # Validate access to the tenant and company
    tenant_id = current_user.get("tenant_id")
    company_id = current_user.get("company_id")

    if not tenant_id or not company_id:
        raise HTTPException(
            status_code=403, detail="Access denied: Tenant or Company not found"
        )

    return db.query(CountryRuleOctService).all()


@router.get(
    "/{permission}/{line}/{fraction}/{country_code}",
    response_model=CountryRuleOctResponseDTO,
)
async def read_country_rule(
    permission: str,
    line: int,
    fraction: str,
    country_code: str,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    """
    Get a specific CountryRuleOct by its composite key.
    """
    # Validate access to the tenant and company
    tenant_id = current_user.get("tenant_id")
    company_id = current_user.get("company_id")

    if not tenant_id or not company_id:
        raise HTTPException(
            status_code=403, detail="Access denied: Tenant or Company not found"
        )

    country = CountryRuleOctService.get_country_by_keys(
        db, permission, line, fraction, country_code
    )
    if not country:
        raise HTTPException(status_code=404, detail="CountryRuleOct not found")
    return country


@router.post(
    "/", response_model=CountryRuleOctResponseDTO, status_code=status.HTTP_201_CREATED
)
async def create_country_rule(
    country_data: CountryRuleOctCreateDTO,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    """
    Create a new CountryRuleOct entry.
    """
    return CountryRuleOctService.create_country_rule(db, country_data)


@router.delete(
    "/{permission}/{line}/{fraction}/{country_code}",
    status_code=status.HTTP_204_NO_CONTENT,
)
async def delete_country_rule(
    permission: str,
    line: int,
    fraction: str,
    country_code: str,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    """
    Delete a CountryRuleOct by its composite key.
    """
    country = CountryRuleOctService.delete_country_rule(
        db, permission, line, fraction, country_code
    )
    if not country:
        raise HTTPException(status_code=404, detail="CountryRuleOct not found")
