"""rename tables to match org schema

Revision ID: 0007
Revises: 0006
Create Date: 2026-02-20 12:00:33.776853

重新命名資料表以符合組織架構規格:
- tenants → organizes
- departments → org_departments
- roles → org_user_roles
- employees → org_employees
- department_members → org_dept_members
- user_role_assignments → org_user_role_assignments
- role_rights → org_role_rights
- email_accounts → org_email_accounts
- network_drives → org_network_drives
- permissions → org_permissions
- audit_logs → org_audit_logs
- batch_logs → org_batch_logs
"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = '0007'
down_revision: Union[str, None] = '0006'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # =========================================================
    # 重新命名資料表（按照依賴順序，從子表到父表）
    # =========================================================

    # 1. 批次作業和日誌表（無外鍵依賴）
    op.rename_table('batch_logs', 'org_batch_logs')
    op.rename_table('audit_logs', 'org_audit_logs')

    # 2. 員工相關子表（依賴 employees）
    op.rename_table('permissions', 'org_permissions')
    op.rename_table('network_drives', 'org_network_drives')
    op.rename_table('email_accounts', 'org_email_accounts')

    # 3. 角色權限相關（依賴 roles）
    op.rename_table('role_rights', 'org_role_rights')
    op.rename_table('user_role_assignments', 'org_user_role_assignments')

    # 4. 部門成員（依賴 departments, employees）
    op.rename_table('department_members', 'org_dept_members')

    # 5. 主要業務表
    op.rename_table('roles', 'org_user_roles')
    op.rename_table('departments', 'org_departments')
    op.rename_table('employees', 'org_employees')

    # 6. 租戶/組織表（最後，因為其他表都依賴它）
    op.rename_table('tenants', 'organizes')


def downgrade() -> None:
    # 反向操作：從父表到子表
    op.rename_table('organizes', 'tenants')
    op.rename_table('org_employees', 'employees')
    op.rename_table('org_departments', 'departments')
    op.rename_table('org_user_roles', 'roles')
    op.rename_table('org_dept_members', 'department_members')
    op.rename_table('org_user_role_assignments', 'user_role_assignments')
    op.rename_table('org_role_rights', 'role_rights')
    op.rename_table('org_email_accounts', 'email_accounts')
    op.rename_table('org_network_drives', 'network_drives')
    op.rename_table('org_permissions', 'permissions')
    op.rename_table('org_audit_logs', 'audit_logs')
    op.rename_table('org_batch_logs', 'batch_logs')
