"""Branchen-Verwaltung in Einstellungen."""

from fastapi import APIRouter, Depends, Form, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session

from dependencies import get_current_user, get_db
from models.branche import Branche, KontaktBranche

router = APIRouter(prefix="/einstellungen/branchen")
templates = Jinja2Templates(directory="templates")


@router.get("", response_class=HTMLResponse)
async def liste(request: Request, user=Depends(get_current_user), db: Session = Depends(get_db)):
    branchen = db.query(Branche).order_by(Branche.sortierung, Branche.name).all()
    return templates.TemplateResponse("pages/einstellungen/branchen.html", {
        "request": request,
        "user": user,
        "active_page": "einstellungen",
        "branchen": branchen,
    })


@router.post("/neu")
async def erstellen(
    name: str = Form(...),
    user=Depends(get_current_user),
    db: Session = Depends(get_db),
):
    existing = db.query(Branche).filter(Branche.name == name.strip()).first()
    if not existing and name.strip():
        max_sort = db.query(Branche).count()
        db.add(Branche(name=name.strip(), sortierung=max_sort))
        db.commit()
    return RedirectResponse(url="/einstellungen/branchen", status_code=303)


@router.post("/{branche_id}/umbenennen")
async def umbenennen(
    branche_id: int,
    name: str = Form(...),
    user=Depends(get_current_user),
    db: Session = Depends(get_db),
):
    branche = db.query(Branche).filter(Branche.id == branche_id).first()
    if branche and name.strip():
        branche.name = name.strip()
        db.commit()
    return RedirectResponse(url="/einstellungen/branchen", status_code=303)


@router.post("/{branche_id}/loeschen")
async def loeschen(
    branche_id: int,
    user=Depends(get_current_user),
    db: Session = Depends(get_db),
):
    branche = db.query(Branche).filter(Branche.id == branche_id).first()
    if branche:
        db.delete(branche)
        db.commit()
    return RedirectResponse(url="/einstellungen/branchen", status_code=303)


@router.post("/{branche_id}/hoch")
async def sortierung_hoch(
    branche_id: int,
    user=Depends(get_current_user),
    db: Session = Depends(get_db),
):
    branchen = db.query(Branche).order_by(Branche.sortierung, Branche.name).all()
    for i, b in enumerate(branchen):
        b.sortierung = i
    db.flush()

    branche = db.query(Branche).filter(Branche.id == branche_id).first()
    if branche and branche.sortierung > 0:
        other = db.query(Branche).filter(Branche.sortierung == branche.sortierung - 1).first()
        if other:
            branche.sortierung, other.sortierung = other.sortierung, branche.sortierung
    db.commit()
    return RedirectResponse(url="/einstellungen/branchen", status_code=303)


@router.post("/{branche_id}/runter")
async def sortierung_runter(
    branche_id: int,
    user=Depends(get_current_user),
    db: Session = Depends(get_db),
):
    branchen = db.query(Branche).order_by(Branche.sortierung, Branche.name).all()
    for i, b in enumerate(branchen):
        b.sortierung = i
    db.flush()

    branche = db.query(Branche).filter(Branche.id == branche_id).first()
    max_sort = db.query(Branche).count() - 1
    if branche and branche.sortierung < max_sort:
        other = db.query(Branche).filter(Branche.sortierung == branche.sortierung + 1).first()
        if other:
            branche.sortierung, other.sortierung = other.sortierung, branche.sortierung
    db.commit()
    return RedirectResponse(url="/einstellungen/branchen", status_code=303)
