from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from app.database import get_db
from app.deps import require_permission
from app.models import GalleryItem, User
from app.schemas import GalleryItemIn, GalleryItemOut, PublicGalleryItemOut

admin_router = APIRouter(prefix="/gallery", tags=["gallery"])
public_router = APIRouter(prefix="/public", tags=["public-gallery"])


def _serialize(row: GalleryItem) -> GalleryItemOut:
    return GalleryItemOut(
        id=row.id,
        title=row.title,
        tag=row.tag,
        image_url=row.image_url,
        is_active=row.is_active,
        sort_order=row.sort_order,
    )


def _public(row: GalleryItem) -> PublicGalleryItemOut:
    return PublicGalleryItemOut(
        id=row.id,
        title=row.title,
        tag=row.tag,
        image_url=row.image_url,
        sort_order=row.sort_order,
    )


@public_router.get("/gallery", response_model=list[PublicGalleryItemOut])
def list_public_gallery(db: Session = Depends(get_db)):
    rows = (
        db.query(GalleryItem)
        .filter(GalleryItem.is_active.is_(True))
        .order_by(GalleryItem.sort_order.asc(), GalleryItem.id.desc())
        .all()
    )
    return [_public(row) for row in rows]


@admin_router.get("", response_model=list[GalleryItemOut])
def list_gallery(db: Session = Depends(get_db), _: User = Depends(require_permission("gallery.view"))):
    rows = db.query(GalleryItem).order_by(GalleryItem.sort_order.asc(), GalleryItem.id.desc()).all()
    return [_serialize(row) for row in rows]


@admin_router.post("", response_model=GalleryItemOut)
def create_gallery_item(
    payload: GalleryItemIn,
    db: Session = Depends(get_db),
    _: User = Depends(require_permission("gallery.create")),
):
    title = payload.title.strip()
    tag = payload.tag.strip() or "Celebration"
    image_url = payload.image_url.strip()
    if not title:
        raise HTTPException(status_code=400, detail="Title is required")
    if not image_url:
        raise HTTPException(status_code=400, detail="Image is required")
    row = GalleryItem(
        title=title,
        tag=tag,
        image_url=image_url,
        is_active=payload.is_active,
        sort_order=payload.sort_order,
    )
    db.add(row)
    db.commit()
    db.refresh(row)
    return _serialize(row)


@admin_router.patch("/{item_id}", response_model=GalleryItemOut)
def update_gallery_item(
    item_id: int,
    payload: GalleryItemIn,
    db: Session = Depends(get_db),
    _: User = Depends(require_permission("gallery.edit")),
):
    row = db.query(GalleryItem).filter(GalleryItem.id == item_id).first()
    if row is None:
        raise HTTPException(status_code=404, detail="Gallery item not found")
    title = payload.title.strip()
    tag = payload.tag.strip() or "Celebration"
    image_url = payload.image_url.strip()
    if not title:
        raise HTTPException(status_code=400, detail="Title is required")
    if not image_url:
        raise HTTPException(status_code=400, detail="Image is required")
    row.title = title
    row.tag = tag
    row.image_url = image_url
    row.is_active = payload.is_active
    row.sort_order = payload.sort_order
    db.commit()
    db.refresh(row)
    return _serialize(row)


@admin_router.delete("/{item_id}")
def delete_gallery_item(
    item_id: int,
    db: Session = Depends(get_db),
    _: User = Depends(require_permission("gallery.delete")),
):
    row = db.query(GalleryItem).filter(GalleryItem.id == item_id).first()
    if row is None:
        raise HTTPException(status_code=404, detail="Gallery item not found")
    db.delete(row)
    db.commit()
    return {"ok": True}
