from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import text
from pydantic import BaseModel
from typing import List, Optional
from app.database import get_db
from app.core.security import require_super_admin
from app.models.system_setting import SystemSetting

router = APIRouter(prefix="/api/settings", tags=["Settings"])

VALID_KEYS = {"maintenance_mode", "development_mode"}


# ── Helpers ───────────────────────────────────────────────────

def _get_setting(db: Session, key: str) -> str:
    row = db.query(SystemSetting).filter(SystemSetting.key == key).first()
    return row.value if row else "false"


def _set_setting(db: Session, key: str, value: str) -> None:
    row = db.query(SystemSetting).filter(SystemSetting.key == key).first()
    if row:
        row.value = value
    else:
        db.add(SystemSetting(key=key, value=value))


# ── GET all settings ──────────────────────────────────────────

@router.get("")
def get_settings(
    db: Session = Depends(get_db),
    _=Depends(require_super_admin),
):
    return {
        "maintenance_mode": _get_setting(db, "maintenance_mode") == "true",
        "development_mode": _get_setting(db, "development_mode") == "true",
    }


# ── PUT update a setting ─────────────────────────────────────

class UpdateSettingRequest(BaseModel):
    key: str
    value: bool


@router.put("")
def update_setting(
    body: UpdateSettingRequest,
    db: Session = Depends(get_db),
    _=Depends(require_super_admin),
):
    if body.key not in VALID_KEYS:
        raise HTTPException(status_code=400, detail=f"Invalid key: {body.key}")
    _set_setting(db, body.key, "true" if body.value else "false")
    try:
        db.commit()
    except Exception:
        db.rollback()
        raise HTTPException(status_code=500, detail="Gagal menyimpan pengaturan")
    return {"key": body.key, "value": body.value}


# ── POST truncate selected tables ─────────────────────────────

TRUNCATABLE = {
    "weekly_schedules": ["assignments", "mass_schedules"],
    "special_events": ["special_positions", "special_subscriptions", "special_masses", "special_events"],
    "daily_subscriptions": ["daily_subscriptions"],
    "shift_swaps": ["shift_swaps"],
    "unavailabilities": ["unavailabilities", "asim_area_unavailabilities"],
}


class TruncateRequest(BaseModel):
    groups: List[str]


@router.post("/truncate")
def truncate_data(
    body: TruncateRequest,
    db: Session = Depends(get_db),
    _=Depends(require_super_admin),
):
    # Only allow in development mode
    if _get_setting(db, "development_mode") != "true":
        raise HTTPException(
            status_code=400,
            detail="Truncate hanya bisa dilakukan saat Development Mode aktif",
        )

    invalid = [g for g in body.groups if g not in TRUNCATABLE]
    if invalid:
        raise HTTPException(status_code=400, detail=f"Invalid groups: {invalid}")

    truncated = []
    try:
        for group in body.groups:
            tables = TRUNCATABLE[group]
            for table in tables:
                db.execute(text(f"TRUNCATE TABLE {table} CASCADE"))
                truncated.append(table)
        db.commit()
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"Gagal truncate: {str(e)}")

    return {"truncated": truncated, "message": f"Berhasil truncate {len(truncated)} tabel"}


# ── GET check maintenance (public, no auth) ──────────────────

public_router = APIRouter(prefix="/api/settings", tags=["Settings"])


@public_router.get("/maintenance-status")
def maintenance_status(db: Session = Depends(get_db)):
    """Public endpoint — frontend checks this on load."""
    return {
        "maintenance_mode": _get_setting(db, "maintenance_mode") == "true",
    }
