from __future__ import annotations

from typing import Annotated

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

from app.api.deps import get_db
from app.schemas.employee import EmployeeCreate, EmployeeMetaRead, EmployeeRead, EmployeeUpdate
from app.services.employee import EmployeeService

router = APIRouter()
DbSession = Annotated[Session, Depends(get_db)]


@router.get("/meta", response_model=EmployeeMetaRead)
def get_employee_meta(db: DbSession) -> EmployeeMetaRead:
    return EmployeeService(db).get_employee_meta()


@router.get("", response_model=list[EmployeeRead])
def list_employees(
    db: DbSession,
    status_filter: Annotated[str | None, Query(alias="status")] = None,
    keyword: str | None = None,
) -> list[EmployeeRead]:
    return EmployeeService(db).list_employees(status=status_filter, keyword=keyword)


@router.post("", response_model=EmployeeRead, status_code=status.HTTP_201_CREATED)
def create_employee(payload: EmployeeCreate, db: DbSession) -> EmployeeRead:
    try:
        return EmployeeService(db).create_employee(payload)
    except ValueError as exc:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc


@router.get("/{employee_id}", response_model=EmployeeRead)
def get_employee(employee_id: str, db: DbSession) -> EmployeeRead:
    employee = EmployeeService(db).get_employee(employee_id)
    if employee is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Employee not found")
    return employee


@router.patch("/{employee_id}", response_model=EmployeeRead)
def update_employee(employee_id: str, payload: EmployeeUpdate, db: DbSession) -> EmployeeRead:
    try:
        return EmployeeService(db).update_employee(employee_id, payload)
    except LookupError as exc:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
    except ValueError as exc:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc


@router.post("/{employee_id}/disable", response_model=EmployeeRead)
def disable_employee(employee_id: str, db: DbSession) -> EmployeeRead:
    try:
        return EmployeeService(db).disable_employee(employee_id)
    except LookupError as exc:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
