from __future__ import annotations

from sqlalchemy import select
from sqlalchemy.orm import Session

from src.apps.admin.models.admin_roles import AdminRole

SCHEDULER_CONFIGS_SEED = [
    {
        "task_name": "fee_settlement.run_daily_fee_sweep",
        "display_name": "Daily Fee Settlement Sweep",
        "description": (
            "Collects all unsettled platform-fee transactions for the current calendar day "
            "and submits a single ACH debit to the HubWallet platform bank account via TSYS TransIT."
        ),
        "schedule_expression": "Daily 23:00 UTC",
        "is_enabled": True,
        "supports_merchant_filter": False,
        "alert_threshold_ms": 60000,
        "log_retention_days": 365,
    },
]

ADMIN_ROLES_SEED = [
    {
        "label": "Admin",
        "slug": "admin",
        "description": (
            "Full platform access. Can manage merchants, admin users, "
            "providers, and settings."
        ),
        "role_rank": 4,
        "is_system": True,
    },
    {
        "label": "Staff",
        "slug": "staff",
        "description": (
            "Read access to all merchants, transactions, invoices, and reports. "
            "Cannot manage users or settings."
        ),
        "role_rank": 2,
        "is_system": True,
    },
    {
        "label": "Customer Support",
        "slug": "customer_support",
        "description": (
            "View merchants, transactions, and invoices. "
            "Focused on handling customer inquiries."
        ),
        "role_rank": 1,
        "is_system": True,
    },
    {
        "label": "Agent",
        "slug": "agent",
        "description": (
            "Access limited to assigned merchants only. "
            "Same view capabilities as Customer Support within scope."
        ),
        "role_rank": 1,
        "is_system": True,
    },
]


def seed_admin_roles(db: Session) -> None:
    """Idempotent — inserts only missing roles by slug."""
    for role_data in ADMIN_ROLES_SEED:
        exists = db.execute(
            select(AdminRole).where(AdminRole.slug == role_data["slug"])
        ).scalar_one_or_none()
        if not exists:
            db.add(AdminRole(**role_data))
    db.commit()


def seed_scheduler_configs(db: Session) -> None:
    """Idempotent — inserts only missing SchedulerConfig rows by task_name."""
    from src.apps.admin.models.scheduler_config import SchedulerConfig

    for cfg in SCHEDULER_CONFIGS_SEED:
        exists = db.execute(
            select(SchedulerConfig).where(SchedulerConfig.task_name == cfg["task_name"])
        ).scalar_one_or_none()
        if not exists:
            db.add(SchedulerConfig(
                task_name=cfg["task_name"],
                display_name=cfg["display_name"],
                description=cfg.get("description"),
                schedule_expression=cfg["schedule_expression"],
                is_enabled=cfg.get("is_enabled", True),
                supports_merchant_filter=cfg.get("supports_merchant_filter", False),
                alert_threshold_ms=cfg.get("alert_threshold_ms"),
                log_retention_days=cfg.get("log_retention_days", 90),
            ))
    db.commit()
