"""YakPanel - Config/Settings API"""
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from pydantic import BaseModel

from app.core.database import get_db
from app.core.config import get_settings, get_runtime_config, set_runtime_config_overrides
from app.core.notification import send_email
from app.api.auth import get_current_user
from app.models.user import User
from app.models.config import Config

router = APIRouter(prefix="/config", tags=["config"])


class ConfigUpdate(BaseModel):
    key: str
    value: str


@router.get("/panel")
async def get_panel_config(
    current_user: User = Depends(get_current_user),
):
    """Get panel configuration (DB overrides applied)"""
    s = get_settings()
    cfg = get_runtime_config()
    return {
        "panel_port": cfg["panel_port"],
        "www_root": cfg["www_root"],
        "setup_path": cfg["setup_path"],
        "webserver_type": cfg["webserver_type"],
        "mysql_root_set": bool(cfg.get("mysql_root")),
        "app_name": s.app_name,
        "app_version": s.app_version,
    }


@router.get("/keys")
async def get_config_keys(
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    """Get all config key-value pairs from DB"""
    result = await db.execute(select(Config).order_by(Config.key))
    rows = result.scalars().all()
    return {r.key: r.value for r in rows}


@router.post("/set")
async def set_config(
    body: ConfigUpdate,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    """Set config value (stored in DB, runtime updated)"""
    result = await db.execute(select(Config).where(Config.key == body.key))
    row = result.scalar_one_or_none()
    if row:
        row.value = body.value
    else:
        db.add(Config(key=body.key, value=body.value))
    await db.commit()
    # Reload runtime config so changes take effect without restart
    r2 = await db.execute(select(Config))
    overrides = {r.key: r.value for r in r2.scalars().all() if r.value is not None}
    set_runtime_config_overrides(overrides)
    return {"status": True, "msg": "Saved"}


@router.post("/test-email")
async def test_email(
    current_user: User = Depends(get_current_user),
):
    """Send a test email to verify SMTP configuration"""
    ok, msg = send_email(
        subject="YakPanel - Test Email",
        body="This is a test email from YakPanel. If you received this, your email configuration is working.",
    )
    if not ok:
        raise HTTPException(status_code=400, detail=msg)
    return {"status": True, "msg": "Test email sent"}
