"""Global auto-delete policy settings."""

from __future__ import annotations

from aiogram import F, Router
from aiogram.fsm.context import FSMContext
from aiogram.types import CallbackQuery, Message

from app.context import AppContext
from app.handlers.common import show
from app.keyboards.inline import auto_delete_menu, back_cancel
from app.states import DeleteState
from app.utils.validation import format_duration, parse_duration_seconds

router = Router(name="auto_delete")


async def _overview(callback: CallbackQuery, ctx: AppContext) -> None:
    enabled = await ctx.app_settings.get_bool("auto_delete_enabled", False)
    user_seconds = await ctx.app_settings.get_int("user_delete_seconds", 0)
    channel_seconds = await ctx.app_settings.get_int("channel_delete_seconds", 0)
    text = (
        "⏱ حذف خودکار پیام‌ها\n\n"
        f"وضعیت: {'روشن' if enabled else 'خاموش'}\n"
        f"پیام ویدیو در چت کاربر: {format_duration(user_seconds)}\n"
        f"پیام پست در کانال: {format_duration(channel_seconds)}\n\n"
        "زمان‌ها از لحظه ارسال واقعی محاسبه می‌شوند و در صف پایدار ذخیره می‌شوند. "
        "اگر ربات هنگام موعد خاموش باشد، حذف پس از راه‌اندازی دوباره انجام می‌شود. "
        "حذف پیام تضمین نمی‌کند کاربر محتوا را ذخیره یا بازنشر نکرده باشد."
    )
    await show(callback, text, auto_delete_menu())


@router.callback_query(F.data == "menu:autodelete")
async def auto_delete_home(callback: CallbackQuery, ctx: AppContext) -> None:
    await _overview(callback, ctx)
    await callback.answer()


@router.callback_query(F.data == "autodel:toggle")
async def auto_delete_toggle(callback: CallbackQuery, ctx: AppContext) -> None:
    current = await ctx.app_settings.get_bool("auto_delete_enabled", False)
    await ctx.app_settings.set("auto_delete_enabled", not current, actor_id=callback.from_user.id)
    await ctx.repos.audit.log(
        callback.from_user.id,
        "settings.auto_delete_toggle",
        entity_type="app_setting",
        entity_id="auto_delete_enabled",
        details={"enabled": not current},
    )
    await callback.answer("وضعیت تغییر کرد.")
    await _overview(callback, ctx)


@router.callback_query(F.data.in_({"autodel:user", "autodel:channel"}))
async def auto_delete_choose(callback: CallbackQuery, state: FSMContext) -> None:
    target = callback.data.rsplit(":", 1)[1]
    await state.set_state(DeleteState.waiting_seconds)
    await state.update_data(delete_target=target)
    await show(
        callback,
        "مدت را به ثانیه یا با پسوند m برای دقیقه و h برای ساعت بفرستید. "
        "مثال: 30، 15m، 2h. برای غیرفعال کردن 0 بفرستید.",
        back_cancel("menu:autodelete"),
    )
    await callback.answer()


@router.message(DeleteState.waiting_seconds)
async def auto_delete_receive(message: Message, state: FSMContext, ctx: AppContext) -> None:
    if not message.text:
        await message.answer("عدد یا مدت معتبر بفرستید.")
        return
    data = await state.get_data()
    target = data.get("delete_target")
    if target not in {"user", "channel"}:
        await state.clear()
        await message.answer("جلسه منقضی شده است.")
        return
    text = message.text.strip().lower()
    if text in {"/cancel", "❌ لغو"}:
        await state.clear()
        await message.answer("لغو شد.")
        return
    try:
        if text in {"0", "off", "خاموش"}:
            seconds = 0
        else:
            seconds = parse_duration_seconds(text)
    except Exception as exc:
        await message.answer(f"⚠️ {exc}")
        return
    key = "user_delete_seconds" if target == "user" else "channel_delete_seconds"
    await ctx.app_settings.set(key, seconds, actor_id=message.from_user.id)
    await ctx.repos.audit.log(
        message.from_user.id,
        "settings.auto_delete_seconds",
        entity_type="app_setting",
        entity_id=key,
        details={"seconds": seconds},
    )
    await state.clear()
    await message.answer(
        f"✅ زمان ذخیره شد: {format_duration(seconds)}",
        reply_markup=back_cancel("menu:autodelete"),
    )
