"""Registro de auditoria."""
from __future__ import annotations

from flask import request, session

from .db import get_db


def log(action: str, detail: str = "", username: str | None = None) -> None:
    user = username or session.get("username") or "sistema"
    ip = request.headers.get("X-Forwarded-For", request.remote_addr or "-").split(",")[0].strip()
    db = get_db()
    db.execute(
        "INSERT INTO audit_log (username, action, detail, ip_address) VALUES (?, ?, ?, ?)",
        (user, action, detail[:2000], ip),
    )
    db.commit()


def recent(limit: int = 10) -> list[dict]:
    rows = get_db().execute(
        "SELECT * FROM audit_log ORDER BY id DESC LIMIT ?", (limit,)
    ).fetchall()
    return [dict(r) for r in rows]


def search(
    username: str = "",
    action: str = "",
    date_from: str = "",
    date_to: str = "",
    page: int = 1,
    per_page: int = 50,
) -> tuple[list[dict], int]:
    where, params = [], []
    if username:
        where.append("username LIKE ?")
        params.append(f"%{username}%")
    if action:
        where.append("action LIKE ?")
        params.append(f"%{action}%")
    if date_from:
        where.append("created_at >= ?")
        params.append(date_from)
    if date_to:
        where.append("created_at <= ?")
        params.append(f"{date_to} 23:59:59")

    clause = f"WHERE {' AND '.join(where)}" if where else ""
    db = get_db()
    total = db.execute(f"SELECT COUNT(*) AS c FROM audit_log {clause}", params).fetchone()["c"]
    offset = max(page - 1, 0) * per_page
    rows = db.execute(
        f"SELECT * FROM audit_log {clause} ORDER BY id DESC LIMIT ? OFFSET ?",
        [*params, per_page, offset],
    ).fetchall()
    return [dict(r) for r in rows], int(total)
