"""consultant communications and service requests phase 5a5 5a6

Revision ID: 20260511_consultant_completion_phase_5a5_5a6
Revises: 20260510_consultant_workspace_phase_5a3
Create Date: 2026-05-11
"""
from __future__ import annotations

from alembic import op
import sqlalchemy as sa


revision = "20260511_consultant_completion_phase_5a5_5a6"
down_revision = "20260510_consultant_workspace_phase_5a3"
branch_labels = None
depends_on = None


def _has_table(bind, table_name: str) -> bool:
    return sa.inspect(bind).has_table(table_name)


def _has_column(bind, table_name: str, column_name: str) -> bool:
    if not _has_table(bind, table_name):
        return False
    return column_name in {col["name"] for col in sa.inspect(bind).get_columns(table_name)}


def upgrade() -> None:
    bind = op.get_bind()

    if not _has_table(bind, "consultant_service_requests"):
        op.create_table(
            "consultant_service_requests",
            sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
            sa.Column("tenant_id", sa.Integer(), sa.ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False),
            sa.Column("branch_id", sa.Integer(), sa.ForeignKey("branches.id"), nullable=True),
            sa.Column("consultant_id", sa.Integer(), sa.ForeignKey("consultant_profiles.id", ondelete="CASCADE"), nullable=False),
            sa.Column("managed_client_id", sa.Integer(), sa.ForeignKey("consultant_managed_clients.id", ondelete="SET NULL"), nullable=True),
            sa.Column("firm_client_id", sa.Integer(), sa.ForeignKey("clients.id", ondelete="SET NULL"), nullable=True),
            sa.Column("service_catalogue_id", sa.Integer(), sa.ForeignKey("service_catalogues.id", ondelete="SET NULL"), nullable=True),
            sa.Column("request_no", sa.String(length=50), nullable=False),
            sa.Column("request_type", sa.String(length=50), nullable=False, server_default="service_request"),
            sa.Column("status", sa.String(length=40), nullable=False, server_default="submitted"),
            sa.Column("priority", sa.String(length=30), nullable=False, server_default="normal"),
            sa.Column("requested_service_name", sa.String(length=200), nullable=False),
            sa.Column("requested_due_date", sa.Date(), nullable=True),
            sa.Column("subject", sa.String(length=255), nullable=False),
            sa.Column("description", sa.Text(), nullable=True),
            sa.Column("consultant_notes", sa.Text(), nullable=True),
            sa.Column("firm_response", sa.Text(), nullable=True),
            sa.Column("created_by_user_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=True),
            sa.Column("updated_by_user_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=True),
            sa.Column("reviewed_by_user_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=True),
            sa.Column("reviewed_at_utc", sa.DateTime(timezone=True), nullable=True),
            sa.Column("created_at_utc", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("CURRENT_TIMESTAMP")),
            sa.Column("updated_at_utc", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("CURRENT_TIMESTAMP")),
            sa.Column("is_active", sa.Boolean(), nullable=False, server_default=sa.text("true")),
        )

    for index_name, columns in {
        "ix_consultant_service_requests_tenant_id": ["tenant_id"],
        "ix_consultant_service_requests_branch_id": ["branch_id"],
        "ix_consultant_service_requests_consultant_id": ["consultant_id"],
        "ix_consultant_service_requests_managed_client_id": ["managed_client_id"],
        "ix_consultant_service_requests_firm_client_id": ["firm_client_id"],
        "ix_consultant_service_requests_service_catalogue_id": ["service_catalogue_id"],
        "ix_consultant_service_requests_request_no": ["request_no"],
        "ix_consultant_service_requests_status": ["status"],
        "ix_consultant_service_requests_priority": ["priority"],
        "ix_consultant_service_requests_is_active": ["is_active"],
    }.items():
        try:
            op.create_index(index_name, "consultant_service_requests", columns)
        except Exception:
            pass

    if _has_table(bind, "service_catalogues") and not _has_column(bind, "service_catalogues", "is_consultant_requestable"):
        with op.batch_alter_table("service_catalogues") as batch_op:
            batch_op.add_column(sa.Column("is_consultant_requestable", sa.Boolean(), nullable=False, server_default=sa.text("false")))


def downgrade() -> None:
    bind = op.get_bind()
    if _has_table(bind, "consultant_service_requests"):
        op.drop_table("consultant_service_requests")
