# app/routers/admin_post.py
from fastapi import APIRouter, Request, Depends, Form, HTTPException
from fastapi.responses import RedirectResponse, HTMLResponse
from pymysql.cursors import DictCursor
from deps import get_db, admin_required

router = APIRouter()

@router.get("/posts", name="posts_index", response_class=HTMLResponse)
def posts_index(req: Request, user = Depends(admin_required)):
    with get_db().cursor(DictCursor) as cur:
        cur.execute("SELECT id,title,slug,locale,is_published,updated_at FROM posts ORDER BY id DESC")
        rows = cur.fetchall()
    return req.app.state.render(req, "posts/index.html", posts=rows, seo={"title": "Posts"})

@router.get("/posts/new", name="posts_new", response_class=HTMLResponse)
def posts_new(req: Request, user = Depends(admin_required)):
    return req.app.state.render(req, "posts/new.html", seo={"title": "New Post"})

@router.post("/posts/new", name="posts_create")
def posts_create(
    req: Request,
    user = Depends(admin_required),
    title: str = Form(...),
    slug: str = Form(...),
    locale: str = Form(...),
    is_published: int = Form(0),
    body_md: str = Form(""),
):
    with get_db().cursor(DictCursor) as cur:
        cur.execute(
            """
            INSERT INTO posts (title, slug, locale, is_published, body_md)
            VALUES (%s,%s,%s,%s,%s)
            """,
            (title, slug, locale, 1 if is_published else 0, body_md),
        )
    # Flash (über Base, optional)
    flashes = req.session.get("_flashes", [])
    flashes.append({"msg": "Post created", "cat": "success"})
    req.session["_flashes"] = flashes
    return RedirectResponse("/admin/posts", status_code=302)

@router.get("/posts/{post_id}/edit", name="posts_edit", response_class=HTMLResponse)
def posts_edit(req: Request, post_id: int, user = Depends(admin_required)):
    with get_db().cursor(DictCursor) as cur:
        cur.execute("SELECT * FROM posts WHERE id=%s", (post_id,))
        row = cur.fetchone()
    if not row:
        return HTMLResponse("Not found", status_code=404)
    return req.app.state.render(req, "posts/edit.html", post=row, seo={"title": f"Edit {row['title']}"})

@router.post("/posts/{post_id}/edit", name="posts_update")
def posts_update(
    req: Request,
    post_id: int,
    user = Depends(admin_required),
    title: str = Form(...),
    slug: str = Form(...),
    locale: str = Form(...),
    is_published: int = Form(0),
    body_md: str = Form(""),
):
    with get_db().cursor(DictCursor) as cur:
        cur.execute(
            """
            UPDATE posts
               SET title=%s, slug=%s, locale=%s, is_published=%s, body_md=%s, updated_at=NOW()
             WHERE id=%s
            """,
            (title, slug, locale, 1 if is_published else 0, body_md, post_id),
        )
    flashes = req.session.get("_flashes", [])
    flashes.append({"msg": "Post updated", "cat": "success"})
    req.session["_flashes"] = flashes
    return RedirectResponse("/admin/posts", status_code=302)
