"""Rename Company/Vendor to Merchant/Store terminology.

Revision ID: t001_terminology
Revises: loyalty_003_phase2
Create Date: 2026-02-06 22:00:00.000000

Major terminology migration:
- companies -> merchants
- vendors -> stores
- company_id -> merchant_id (in all child tables)
- vendor_id -> store_id (in all child tables)
- vendor_code -> store_code
- letzshop_vendor_id -> letzshop_store_id
- letzshop_vendor_slug -> letzshop_store_slug
- vendor_name -> store_name (in marketplace_products)
- All vendor-prefixed tables renamed to store-prefixed
- company_loyalty_settings -> merchant_loyalty_settings
- letzshop_vendor_cache -> letzshop_store_cache
"""

from collections.abc import Sequence

from sqlalchemy import text

from alembic import op

# revision identifiers, used by Alembic.
revision: str = "t001_terminology"
down_revision: str | None = "loyalty_003_phase2"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def _col_exists(table: str, col: str) -> bool:
    """Check if column exists using raw SQL."""
    conn = op.get_bind()
    result = conn.execute(text(
        "SELECT 1 FROM information_schema.columns "
        "WHERE table_schema='public' AND table_name=:t AND column_name=:c"
    ), {"t": table, "c": col})
    return result.fetchone() is not None


def _table_exists(table: str) -> bool:
    """Check if table exists using raw SQL."""
    conn = op.get_bind()
    result = conn.execute(text(
        "SELECT 1 FROM information_schema.tables "
        "WHERE table_schema='public' AND table_name=:t"
    ), {"t": table})
    return result.fetchone() is not None


def upgrade() -> None:
    """Rename all Company/Vendor references to Merchant/Store."""

    # ======================================================================
    # STEP 1: Rename columns in child tables FIRST (before renaming parent tables)
    # ======================================================================

    # --- company_id -> merchant_id ---
    op.alter_column("vendors", "company_id", new_column_name="merchant_id")
    # Loyalty tables: loyalty_003 already added merchant_id as a new column,
    # so company_id only exists on legacy databases (pre-loyalty_003).
    if _col_exists("loyalty_programs", "company_id"):
        op.alter_column("loyalty_programs", "company_id", new_column_name="merchant_id")
    if _col_exists("loyalty_cards", "company_id"):
        op.alter_column("loyalty_cards", "company_id", new_column_name="merchant_id")
    if _col_exists("loyalty_transactions", "company_id"):
        op.alter_column("loyalty_transactions", "company_id", new_column_name="merchant_id")
    if _table_exists("company_loyalty_settings"):
        op.alter_column("company_loyalty_settings", "company_id", new_column_name="merchant_id")
    if _col_exists("staff_pins", "company_id"):
        op.alter_column("staff_pins", "company_id", new_column_name="merchant_id")

    # --- vendor_id -> store_id (in all child tables) ---
    op.alter_column("products", "vendor_id", new_column_name="store_id")
    op.alter_column("customers", "vendor_id", new_column_name="store_id")
    op.alter_column("customer_addresses", "vendor_id", new_column_name="store_id")
    op.alter_column("orders", "vendor_id", new_column_name="store_id")
    op.alter_column("order_item_exceptions", "vendor_id", new_column_name="store_id")
    op.alter_column("invoices", "vendor_id", new_column_name="store_id")
    op.alter_column("inventory", "vendor_id", new_column_name="store_id")
    op.alter_column("inventory_transactions", "vendor_id", new_column_name="store_id")
    op.alter_column("marketplace_import_jobs", "vendor_id", new_column_name="store_id")
    op.alter_column("letzshop_fulfillment_queue", "vendor_id", new_column_name="store_id")
    op.alter_column("letzshop_sync_logs", "vendor_id", new_column_name="store_id")
    op.alter_column("letzshop_historical_import_jobs", "vendor_id", new_column_name="store_id")
    op.alter_column("vendor_users", "vendor_id", new_column_name="store_id")
    op.alter_column("roles", "vendor_id", new_column_name="store_id")
    op.alter_column("vendor_domains", "vendor_id", new_column_name="store_id")
    op.alter_column("vendor_platforms", "vendor_id", new_column_name="store_id")
    op.alter_column("vendor_addons", "vendor_id", new_column_name="store_id")
    if _table_exists("vendor_subscriptions"):
        op.alter_column("vendor_subscriptions", "vendor_id", new_column_name="store_id")
    op.alter_column("billing_history", "vendor_id", new_column_name="store_id")
    op.alter_column("content_pages", "vendor_id", new_column_name="store_id")
    op.alter_column("vendor_themes", "vendor_id", new_column_name="store_id")
    op.alter_column("media_files", "vendor_id", new_column_name="store_id")
    op.alter_column("vendor_email_templates", "vendor_id", new_column_name="store_id")
    op.alter_column("vendor_email_settings", "vendor_id", new_column_name="store_id")
    op.alter_column("vendor_letzshop_credentials", "vendor_id", new_column_name="store_id")
    op.alter_column("vendor_onboarding", "vendor_id", new_column_name="store_id")
    op.alter_column("vendor_invoice_settings", "vendor_id", new_column_name="store_id")
    op.alter_column("staff_pins", "vendor_id", new_column_name="store_id")
    op.alter_column("loyalty_cards", "enrolled_at_vendor_id", new_column_name="enrolled_at_store_id")
    op.alter_column("loyalty_transactions", "vendor_id", new_column_name="store_id")

    # Columns that may not exist yet (defined in models but not yet migrated)
    if _col_exists("letzshop_fulfillment_queue", "claimed_by_vendor_id"):
        op.alter_column("letzshop_fulfillment_queue", "claimed_by_vendor_id", new_column_name="claimed_by_store_id")
    if _col_exists("admin_audit_logs", "vendor_id"):
        op.alter_column("admin_audit_logs", "vendor_id", new_column_name="store_id")
    if _col_exists("messages", "vendor_id"):
        op.alter_column("messages", "vendor_id", new_column_name="store_id")
    if _col_exists("conversations", "vendor_id"):
        op.alter_column("conversations", "vendor_id", new_column_name="store_id")
    if _table_exists("emails") and _col_exists("emails", "vendor_id"):
        op.alter_column("emails", "vendor_id", new_column_name="store_id")
    if _table_exists("carts") and _col_exists("carts", "vendor_id"):
        op.alter_column("carts", "vendor_id", new_column_name="store_id")

    # --- Other vendor-prefixed columns ---
    op.alter_column("vendors", "vendor_code", new_column_name="store_code")
    op.alter_column("vendors", "letzshop_vendor_id", new_column_name="letzshop_store_id")
    op.alter_column("vendors", "letzshop_vendor_slug", new_column_name="letzshop_store_slug")
    op.alter_column("marketplace_products", "vendor_name", new_column_name="store_name")

    # ======================================================================
    # STEP 2: Rename parent tables
    # ======================================================================
    op.rename_table("companies", "merchants")
    op.rename_table("vendors", "stores")

    # ======================================================================
    # STEP 3: Rename vendor-prefixed child tables
    # ======================================================================
    op.rename_table("vendor_users", "store_users")
    op.rename_table("vendor_domains", "store_domains")
    op.rename_table("vendor_platforms", "store_platforms")
    op.rename_table("vendor_themes", "store_themes")
    op.rename_table("vendor_email_templates", "store_email_templates")
    op.rename_table("vendor_email_settings", "store_email_settings")
    op.rename_table("vendor_addons", "store_addons")
    if _table_exists("vendor_subscriptions"):
        op.rename_table("vendor_subscriptions", "store_subscriptions")
    op.rename_table("vendor_letzshop_credentials", "store_letzshop_credentials")
    op.rename_table("vendor_onboarding", "store_onboarding")
    op.rename_table("vendor_invoice_settings", "store_invoice_settings")
    if _table_exists("company_loyalty_settings"):
        op.rename_table("company_loyalty_settings", "merchant_loyalty_settings")
    op.rename_table("letzshop_vendor_cache", "letzshop_store_cache")


def downgrade() -> None:
    """Revert all Merchant/Store references back to Company/Vendor."""

    # STEP 1: Revert table renames
    op.rename_table("letzshop_store_cache", "letzshop_vendor_cache")
    if _table_exists("merchant_loyalty_settings"):
        op.rename_table("merchant_loyalty_settings", "company_loyalty_settings")
    op.rename_table("store_invoice_settings", "vendor_invoice_settings")
    op.rename_table("store_onboarding", "vendor_onboarding")
    op.rename_table("store_letzshop_credentials", "vendor_letzshop_credentials")
    if _table_exists("store_subscriptions"):
        op.rename_table("store_subscriptions", "vendor_subscriptions")
    op.rename_table("store_addons", "vendor_addons")
    op.rename_table("store_email_settings", "vendor_email_settings")
    op.rename_table("store_email_templates", "vendor_email_templates")
    op.rename_table("store_themes", "vendor_themes")
    op.rename_table("store_platforms", "vendor_platforms")
    op.rename_table("store_domains", "vendor_domains")
    op.rename_table("store_users", "vendor_users")
    op.rename_table("stores", "vendors")
    op.rename_table("merchants", "companies")

    # STEP 2: Revert column renames
    op.alter_column("vendors", "store_code", new_column_name="vendor_code")
    op.alter_column("vendors", "letzshop_store_id", new_column_name="letzshop_vendor_id")
    op.alter_column("vendors", "letzshop_store_slug", new_column_name="letzshop_vendor_slug")
    op.alter_column("marketplace_products", "store_name", new_column_name="vendor_name")

    op.alter_column("vendors", "merchant_id", new_column_name="company_id")
    # Loyalty tables: only reverse if t001 upgrade actually renamed company_id.
    # On fresh DBs, loyalty_003 owns merchant_id — don't touch it.
    if _col_exists("loyalty_programs", "company_id"):
        pass  # Already reverted or was never renamed
    elif _col_exists("loyalty_programs", "merchant_id") and not _table_exists("loyalty_programs"):
        pass  # Table gone, skip
    elif _col_exists("loyalty_programs", "merchant_id"):
        # Check if this is a legacy DB where company_id was renamed to merchant_id.
        # If loyalty_003 added merchant_id (fresh DB), store_id won't exist
        # (loyalty_003 removed it). Only rename if store_id exists (legacy path).
        if _col_exists("loyalty_programs", "store_id"):
            op.alter_column("loyalty_programs", "merchant_id", new_column_name="company_id")
    if _col_exists("loyalty_cards", "merchant_id") and _col_exists("loyalty_cards", "store_id"):
        op.alter_column("loyalty_cards", "merchant_id", new_column_name="company_id")
    if _col_exists("loyalty_transactions", "merchant_id") and _col_exists("loyalty_transactions", "store_id"):
        op.alter_column("loyalty_transactions", "merchant_id", new_column_name="company_id")
    if _table_exists("company_loyalty_settings") and _col_exists("company_loyalty_settings", "merchant_id"):
        op.alter_column("company_loyalty_settings", "merchant_id", new_column_name="company_id")
    if _col_exists("staff_pins", "merchant_id") and _col_exists("staff_pins", "store_id"):
        op.alter_column("staff_pins", "merchant_id", new_column_name="company_id")

    op.alter_column("products", "store_id", new_column_name="vendor_id")
    op.alter_column("customers", "store_id", new_column_name="vendor_id")
    op.alter_column("customer_addresses", "store_id", new_column_name="vendor_id")
    op.alter_column("orders", "store_id", new_column_name="vendor_id")
    op.alter_column("order_item_exceptions", "store_id", new_column_name="vendor_id")
    op.alter_column("invoices", "store_id", new_column_name="vendor_id")
    op.alter_column("inventory", "store_id", new_column_name="vendor_id")
    op.alter_column("inventory_transactions", "store_id", new_column_name="vendor_id")
    op.alter_column("marketplace_import_jobs", "store_id", new_column_name="vendor_id")
    op.alter_column("letzshop_fulfillment_queue", "store_id", new_column_name="vendor_id")
    op.alter_column("letzshop_sync_logs", "store_id", new_column_name="vendor_id")
    op.alter_column("letzshop_historical_import_jobs", "store_id", new_column_name="vendor_id")
    op.alter_column("vendor_users", "store_id", new_column_name="vendor_id")
    op.alter_column("roles", "store_id", new_column_name="vendor_id")
    op.alter_column("vendor_domains", "store_id", new_column_name="vendor_id")
    op.alter_column("vendor_platforms", "store_id", new_column_name="vendor_id")
    op.alter_column("vendor_addons", "store_id", new_column_name="vendor_id")
    if _table_exists("vendor_subscriptions"):
        op.alter_column("vendor_subscriptions", "store_id", new_column_name="vendor_id")
    op.alter_column("billing_history", "store_id", new_column_name="vendor_id")
    op.alter_column("content_pages", "store_id", new_column_name="vendor_id")
    op.alter_column("vendor_themes", "store_id", new_column_name="vendor_id")
    op.alter_column("media_files", "store_id", new_column_name="vendor_id")
    op.alter_column("vendor_email_templates", "store_id", new_column_name="vendor_id")
    op.alter_column("vendor_email_settings", "store_id", new_column_name="vendor_id")
    op.alter_column("vendor_letzshop_credentials", "store_id", new_column_name="vendor_id")
    op.alter_column("vendor_onboarding", "store_id", new_column_name="vendor_id")
    op.alter_column("vendor_invoice_settings", "store_id", new_column_name="vendor_id")
    op.alter_column("staff_pins", "store_id", new_column_name="vendor_id")
    op.alter_column("loyalty_cards", "enrolled_at_store_id", new_column_name="enrolled_at_vendor_id")
    op.alter_column("loyalty_transactions", "store_id", new_column_name="vendor_id")

    # Conditional columns
    if _col_exists("letzshop_fulfillment_queue", "claimed_by_store_id"):
        op.alter_column("letzshop_fulfillment_queue", "claimed_by_store_id", new_column_name="claimed_by_vendor_id")
    if _col_exists("admin_audit_logs", "store_id"):
        op.alter_column("admin_audit_logs", "store_id", new_column_name="vendor_id")
    if _col_exists("messages", "store_id"):
        op.alter_column("messages", "store_id", new_column_name="vendor_id")
    if _col_exists("conversations", "store_id"):
        op.alter_column("conversations", "store_id", new_column_name="vendor_id")
    if _table_exists("emails") and _col_exists("emails", "store_id"):
        op.alter_column("emails", "store_id", new_column_name="vendor_id")
    if _table_exists("carts") and _col_exists("carts", "store_id"):
        op.alter_column("carts", "store_id", new_column_name="vendor_id")
