"""Client groups and family tracking.

Revision ID: 20260725_client_groups_family_tracking
Revises: 20260723_phase6_pan_login_client_identity
"""
from alembic import op
import sqlalchemy as sa

revision = "20260725_client_groups_family_tracking"
down_revision = "20260723_phase6_pan_login_client_identity"
branch_labels = None
depends_on = None


def upgrade():
    op.create_table(
        "client_groups",
        sa.Column("id", sa.Integer(), primary_key=True),
        sa.Column("tenant_id", sa.Integer(), sa.ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False),
        sa.Column("group_code", sa.String(50), nullable=False),
        sa.Column("group_name", sa.String(200), nullable=False),
        sa.Column("group_type", sa.String(50), nullable=False, server_default="Family"),
        sa.Column("primary_contact_name", sa.String(200)), sa.Column("primary_contact_mobile", sa.String(20)), sa.Column("primary_contact_email", sa.String(255)),
        sa.Column("assigned_partner_user_id", sa.Integer(), sa.ForeignKey("users.id", ondelete="SET NULL")),
        sa.Column("primary_consultant_id", sa.Integer(), sa.ForeignKey("consultant_profiles.id", ondelete="SET NULL")),
        sa.Column("notes", sa.Text()), sa.Column("is_active", sa.Boolean(), nullable=False, server_default=sa.true()),
        sa.Column("created_by_user_id", sa.Integer(), sa.ForeignKey("users.id", ondelete="SET NULL")), sa.Column("updated_by_user_id", sa.Integer(), sa.ForeignKey("users.id", ondelete="SET NULL")),
        sa.Column("created_at_utc", sa.DateTime(timezone=True), nullable=False), sa.Column("updated_at_utc", sa.DateTime(timezone=True), nullable=False),
        sa.UniqueConstraint("tenant_id", "group_code", name="uq_client_groups_tenant_code"),
    )
    for c in ("tenant_id","group_code","group_name","group_type","assigned_partner_user_id","primary_consultant_id","is_active"):
        op.create_index(f"ix_client_groups_{c}", "client_groups", [c])
    op.add_column("clients", sa.Column("client_group_id", sa.Integer(), nullable=True))
    op.add_column("clients", sa.Column("group_relationship", sa.String(100), nullable=True))
    op.add_column("clients", sa.Column("is_group_head", sa.Boolean(), nullable=False, server_default=sa.false()))
    op.create_foreign_key("fk_clients_client_group_id", "clients", "client_groups", ["client_group_id"], ["id"], ondelete="SET NULL")
    op.create_index("ix_clients_client_group_id", "clients", ["client_group_id"])
    op.create_index("ix_clients_is_group_head", "clients", ["is_group_head"])


def downgrade():
    op.drop_index("ix_clients_is_group_head", table_name="clients")
    op.drop_index("ix_clients_client_group_id", table_name="clients")
    op.drop_constraint("fk_clients_client_group_id", "clients", type_="foreignkey")
    op.drop_column("clients", "is_group_head"); op.drop_column("clients", "group_relationship"); op.drop_column("clients", "client_group_id")
    op.drop_table("client_groups")
