# -*- coding: utf-8 -*-
"""Location: ./mcpgateway/alembic/versions/0f81d4a5efe0_new_table_email_team_member_history_for_.py
Copyright 2026
SPDX-License-Identifier: Apache-2.0
Authors: Mihai Criveti

new table email_team_member_history for audit trail of action performed on team members

Revision ID: 0f81d4a5efe0
Revises: 14ac971cee42
Create Date: 2025-09-15 14:53:32.682953
"""

# Standard
from datetime import datetime, timezone
from typing import Sequence, Union
import uuid

# Third-Party
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision: str = "0f81d4a5efe0"
down_revision: Union[str, Sequence[str], None] = "14ac971cee42"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    """Upgrade schema."""
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "email_team_member_history",
        sa.Column("id", sa.String(36), nullable=False),
        sa.Column("team_member_id", sa.String(36), nullable=False),
        sa.Column("team_id", sa.String(36), nullable=False),
        sa.Column("user_email", sa.String(255), nullable=False),
        sa.Column("role", sa.String(50), nullable=False, server_default=sa.text("'member'")),
        sa.Column("action", sa.String(50), nullable=False),
        sa.Column("action_by", sa.String(255), nullable=True),
        sa.Column("action_timestamp", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
        sa.PrimaryKeyConstraint("id"),
        sa.ForeignKeyConstraint(["team_member_id"], ["email_team_members.id"]),
        sa.ForeignKeyConstraint(["team_id"], ["email_teams.id"]),
        sa.ForeignKeyConstraint(["user_email"], ["email_users.email"]),
        sa.ForeignKeyConstraint(["action_by"], ["email_users.email"]),
    )

    # Insert one audit entry for each existing team member
    bind = op.get_bind()

    # Use database-agnostic query for boolean columns
    # PostgreSQL uses TRUE/FALSE, SQLite uses 1/0
    if bind.dialect.name == "postgresql":
        # For PostgreSQL, use proper boolean comparison
        result = bind.execute(sa.text("""
            SELECT id, team_id, user_email, role
            FROM email_team_members
            WHERE is_active = TRUE
        """))
    else:
        # For SQLite, use integer comparison
        result = bind.execute(sa.text("""
            SELECT id, team_id, user_email, role
            FROM email_team_members
            WHERE is_active = 1
        """))

    # Process results and insert history records
    for row in result:
        history_id = uuid.uuid4().hex
        bind.execute(
            sa.text(
                "INSERT INTO email_team_member_history (id, team_member_id, team_id, user_email, role, action, action_by, action_timestamp) "
                "VALUES (:id, :team_member_id, :team_id, :user_email, :role, :action, :action_by, :action_timestamp)"
            ),
            {
                "id": history_id,
                "team_member_id": row[0],
                "team_id": row[1],
                "user_email": row[2],
                "role": row[3] if row[3] else "member",
                "action": "migrated",
                "action_by": None,
                "action_timestamp": datetime.now(timezone.utc),
            },
        )
    # ### end Alembic commands ###


def downgrade() -> None:
    """Downgrade schema."""
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table("email_team_member_history")
    # ### end Alembic commands ###
