"""
Product Category seeder — creates default categories for new merchants.
"""
import logging
from sqlalchemy.orm import Session
from sqlalchemy import select

from src.apps.product_categories.models.product_category import ProductCategory

logger = logging.getLogger(__name__)


async def seed_default_categories(merchant_id: int, db: Session) -> None:
    """
    Idempotent — creates a default "General" category for the merchant.
    Safe to call multiple times; will not duplicate.
    """
    try:
        existing = db.execute(
            select(ProductCategory).where(
                ProductCategory.merchant_id == merchant_id,
                ProductCategory.code == "general",
                ProductCategory.deleted_at.is_(None),
            )
        ).scalar_one_or_none()

        if existing:
            logger.info(f"Default category already exists for merchant {merchant_id}")
            return

        default_category = ProductCategory(
            name="General",
            code="general",
            slug="general",
            is_active=True,
            order=1,
            parent_id=None,
            merchant_id=merchant_id,
        )
        db.add(default_category)
        db.commit()
        logger.info(f"Seeded default 'General' category for merchant {merchant_id}")

    except Exception as e:
        logger.error(f"Error seeding default categories for merchant {merchant_id}: {e}")
        db.rollback()
