from fastapi import APIRouter, Request, Form, Depends
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.core.database import get_db
from app.models.models import MikrotikConfig
from app.core.security import require_roles
from app.core.secrets import encrypt_secret
import os

router = APIRouter(dependencies=[Depends(require_roles("super_admin", "admin_cs"))])
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "app/templates"))

@router.get("/settings/mikrotik", response_class=HTMLResponse)
async def mikrotik_settings_page(request: Request, db: AsyncSession = Depends(get_db)):
    result = await db.execute(select(MikrotikConfig).limit(1))
    config = result.scalar_one_or_none()
    return templates.TemplateResponse(request=request, name="mikrotik_settings.html", context={"config": config})

@router.post("/settings/mikrotik")
async def save_mikrotik_settings(
    host: str = Form(...),
    username: str = Form(...),
    password: str = Form(""),
    db: AsyncSession = Depends(get_db)
):
    result = await db.execute(select(MikrotikConfig).limit(1))
    config = result.scalar_one_or_none()
    
    if config:
        config.host = host
        config.username = username
        if password:
            config.password = encrypt_secret(password)
    else:
        config = MikrotikConfig(host=host, username=username, password=encrypt_secret(password))
        db.add(config)
    
    await db.commit()
    return RedirectResponse(url="/settings/mikrotik", status_code=303)
