"""seed platform service registry and base features

Revision ID: 0006_platform_catalog_seed
Revises: 0005_tenant_onboarding
Create Date: 2026-07-27
"""
from __future__ import annotations

import uuid
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

revision: str = "0006_platform_catalog_seed"
down_revision: Union[str, None] = "0005_tenant_onboarding"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None

SERVICES = [
    ("accounting", "حسابداری آنلاین", "http://accounting-service:8002"),
    ("healthcare", "تربت هلث", "http://healthcare-service:8010"),
    ("beauty", "تربت بیوتی", "http://beauty-business-service:8011"),
    ("crm", "سیستم CRM", "http://crm-service:8003"),
    ("loyalty", "تربت وفاداری", "http://loyalty-service:8004"),
    ("communication", "ارتباطات و پیامک", "http://communication-service:8005"),
    ("sports_center", "مرکز ورزشی", "http://sports-center-service:8006"),
    ("delivery", "تربت درایور", "http://delivery-service:8007"),
    ("experience", "پلتفرم تجربه", "http://experience-service:8008"),
    ("hospitality", "تربت فود", "http://hospitality-service:8009"),
    ("identity", "هویت و دسترسی", "http://identity-access-service:8001"),
]

FEATURES = [
    ("accounting.access", "دسترسی حسابداری", "accounting"),
    ("healthcare.access", "دسترسی سلامت", "healthcare"),
    ("beauty.access", "دسترسی زیبایی", "beauty"),
    ("crm.access", "دسترسی CRM", "crm"),
    ("loyalty.access", "دسترسی وفاداری", "loyalty"),
    ("communication.access", "دسترسی ارتباطات", "communication"),
    ("sports_center.access", "دسترسی مرکز ورزشی", "sports_center"),
    ("delivery.access", "دسترسی لجستیک", "delivery"),
    ("experience.access", "دسترسی تجربه", "experience"),
    ("hospitality.access", "دسترسی رستوران", "hospitality"),
]


def upgrade() -> None:
    for service_key, name, base_url in SERVICES:
        op.execute(
            sa.text(
                """
                INSERT INTO service_registry (id, service_key, name, base_url, health_check_url, status)
                VALUES (CAST(:id AS uuid), :service_key, :name, :base_url, :health_url, 'active')
                ON CONFLICT (service_key) DO NOTHING
                """
            ).bindparams(
                id=str(uuid.uuid4()),
                service_key=service_key,
                name=name,
                base_url=base_url,
                health_url=f"{base_url}/health",
            )
        )

    for feature_key, name, service_key in FEATURES:
        op.execute(
            sa.text(
                """
                INSERT INTO features (id, feature_key, name, description, service_key, is_active)
                VALUES (CAST(:id AS uuid), :feature_key, :name, :description, :service_key, true)
                ON CONFLICT (feature_key) DO NOTHING
                """
            ).bindparams(
                id=str(uuid.uuid4()),
                feature_key=feature_key,
                name=name,
                description=f"دسترسی پایه به سرویس {service_key}",
                service_key=service_key,
            )
        )

    for feature_key, _, _ in FEATURES:
        op.execute(
            sa.text(
                """
                INSERT INTO plan_features (id, plan_id, feature_id, is_enabled)
                SELECT CAST(:id AS uuid), p.id, f.id, true
                FROM plans p
                CROSS JOIN features f
                WHERE p.code = 'FREE' AND f.feature_key = :feature_key
                ON CONFLICT (plan_id, feature_id) DO NOTHING
                """
            ).bindparams(id=str(uuid.uuid4()), feature_key=feature_key)
        )


def downgrade() -> None:
    feature_keys = ", ".join(f"'{key}'" for key, _, _ in FEATURES)
    service_keys = ", ".join(f"'{key}'" for key, _, _ in SERVICES)
    op.execute(f"DELETE FROM plan_features WHERE feature_id IN (SELECT id FROM features WHERE feature_key IN ({feature_keys}))")
    op.execute(f"DELETE FROM features WHERE feature_key IN ({feature_keys})")
    op.execute(f"DELETE FROM service_registry WHERE service_key IN ({service_keys})")
