from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, EmailStr
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.auth import requires_role, get_current_user
from app.models.config import Config   # Key/Value Tabelle: key (pk), value (text)

router = APIRouter(prefix="/admin/settings", tags=["admin-settings"], dependencies=[Depends(requires_role("admin","manager"))])

class PaypalCfg(BaseModel):
    paypal_me: str | None = None
    paypal_receiver: EmailStr | None = None

@router.get("/paypal", response_model=PaypalCfg)
def get_paypal(db: Session = Depends(get_db)):
    def get(key): 
        obj = db.query(Config).get(key)
        return obj.value if obj else None
    return PaypalCfg(
        paypal_me=get("paypal_me") or None,
        paypal_receiver=get("paypal_receiver") or None
    )

@router.put("/paypal", response_model=PaypalCfg)
def put_paypal(cfg: PaypalCfg, db: Session = Depends(get_db), user=Depends(get_current_user)):
    for k,v in [("paypal_me", cfg.paypal_me), ("paypal_receiver", cfg.paypal_receiver)]:
        row = db.query(Config).get(k)
        if row: row.value = v or ""
        else: db.add(Config(key=k, value=v or ""))
    db.commit()
    return cfg
