import secrets
import uuid
from passlib.context import CryptContext
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from auth_utils import get_current_admin
from database import get_db
from models.site import Site
from schemas.site import SiteCreate, SiteUpdate, SiteOut, SiteCreatedOut, LockRequest

router = APIRouter()
_pwd = CryptContext(schemes=["bcrypt"], deprecated="auto")


@router.get("/", response_model=list[SiteOut])
def list_sites(db: Session = Depends(get_db), _=Depends(get_current_admin)):
    return db.query(Site).all()


@router.post("/", response_model=SiteCreatedOut, status_code=status.HTTP_201_CREATED)
def create_site(body: SiteCreate, db: Session = Depends(get_db), _=Depends(get_current_admin)):
    raw_key = secrets.token_urlsafe(32)
    site = Site(
        site_id=str(uuid.uuid4()),
        name=body.name,
        owner_name=body.owner_name,
        contact_email=body.contact_email,
        secret_key_hash=_pwd.hash(raw_key),
        license_expires_at=body.license_expires_at,
    )
    db.add(site)
    db.commit()
    db.refresh(site)
    data = SiteOut.model_validate(site).model_dump()
    data["secret_key"] = raw_key
    return SiteCreatedOut(**data)


@router.get("/{site_id}", response_model=SiteOut)
def get_site(site_id: str, db: Session = Depends(get_db), _=Depends(get_current_admin)):
    site = db.query(Site).filter(Site.site_id == site_id).first()
    if not site:
        raise HTTPException(status_code=404, detail="Site not found")
    return site


@router.put("/{site_id}", response_model=SiteOut)
def update_site(site_id: str, body: SiteUpdate, db: Session = Depends(get_db), _=Depends(get_current_admin)):
    site = db.query(Site).filter(Site.site_id == site_id).first()
    if not site:
        raise HTTPException(status_code=404, detail="Site not found")
    for field, value in body.model_dump(exclude_none=True).items():
        setattr(site, field, value)
    db.commit()
    db.refresh(site)
    return site


@router.post("/{site_id}/lock", response_model=SiteOut)
def lock_site(site_id: str, body: LockRequest, db: Session = Depends(get_db), _=Depends(get_current_admin)):
    site = db.query(Site).filter(Site.site_id == site_id).first()
    if not site:
        raise HTTPException(status_code=404, detail="Site not found")
    site.is_locked = True
    site.lock_reason = body.reason
    db.commit()
    db.refresh(site)
    return site


@router.post("/{site_id}/unlock", response_model=SiteOut)
def unlock_site(site_id: str, db: Session = Depends(get_db), _=Depends(get_current_admin)):
    site = db.query(Site).filter(Site.site_id == site_id).first()
    if not site:
        raise HTTPException(status_code=404, detail="Site not found")
    site.is_locked = False
    site.lock_reason = None
    db.commit()
    db.refresh(site)
    return site


@router.delete("/{site_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_site(site_id: str, db: Session = Depends(get_db), _=Depends(get_current_admin)):
    site = db.query(Site).filter(Site.site_id == site_id).first()
    if not site:
        raise HTTPException(status_code=404, detail="Site not found")
    db.delete(site)
    db.commit()
