from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from starlette.requests import Request

from app.core.rbac import require_permission
from app.db.database import get_db
from app.models.user import User
from app.schemas.system_setting import (
    PublicLinksSettingsResponse,
    PublicLinksSettingsUpdate,
    SmtpSettingsResponse,
    SmtpSettingsUpdate,
    SmtpTestRequest,
    SmtpTestResponse,
)
from app.services.system_settings_service import SystemSettingsService

router = APIRouter(
    prefix="/system-settings",
    tags=["System Settings"],
)


@router.get("/smtp", response_model=SmtpSettingsResponse)
def get_smtp_settings(
    db: Session = Depends(get_db),
    current_user: User = Depends(require_permission("system_settings.manage")),
):
    return SystemSettingsService.get_smtp_settings(db)


@router.put("/smtp", response_model=SmtpSettingsResponse)
def update_smtp_settings(
    payload: SmtpSettingsUpdate,
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_permission("system_settings.manage")),
):
    return SystemSettingsService.update_smtp_settings(db, payload, actor=current_user, request=request)


@router.post("/smtp/test", response_model=SmtpTestResponse)
def send_smtp_test_mail(
    payload: SmtpTestRequest,
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_permission("system_settings.manage")),
):
    return SystemSettingsService.send_test_mail(db, payload.recipient, actor=current_user, request=request)


@router.get("/public-links", response_model=PublicLinksSettingsResponse)
def get_public_links_settings(
    db: Session = Depends(get_db),
    current_user: User = Depends(require_permission("system_settings.manage")),
):
    return SystemSettingsService.get_public_links_settings(db)


@router.put("/public-links", response_model=PublicLinksSettingsResponse)
def update_public_links_settings(
    payload: PublicLinksSettingsUpdate,
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_permission("system_settings.manage")),
):
    return SystemSettingsService.update_public_links_settings(db, payload, actor=current_user, request=request)
