"""Unify entity_type 'company' to 'contact' across all plugins.

Revision ID: 0027
Revises: 0026_mail_salt_security
Create Date: 2026-07-23

Changes:
- UPDATE entity_links SET entity_type='contact' WHERE entity_type='company'
- UPDATE tag_assignments SET entity_type='contact' WHERE entity_type='company'
- UPDATE calendar_entry_links SET entity_type='contact' WHERE entity_type='company'
- UPDATE addresses SET entity_type='contact' WHERE entity_type='company'
- ALTER TABLE mails RENAME COLUMN company_id TO contact_id (if exists)
"""
from alembic import op
import sqlalchemy as sa


revision = "0027_unify_company_to_contact"
down_revision = "0026_mail_salt_security"


def upgrade():
    # Update entity_links: company -> contact
    op.execute(
        "UPDATE entity_links SET entity_type = 'contact' WHERE entity_type = 'company'"
    )
    # Update tag_assignments: company -> contact
    op.execute(
        "UPDATE tag_assignments SET entity_type = 'contact' WHERE entity_type = 'company'"
    )
    # Update calendar_entry_links: company -> contact
    op.execute(
        "UPDATE calendar_entry_links SET entity_type = 'contact' WHERE entity_type = 'company'"
    )
    # Update addresses: company -> contact
    op.execute(
        "UPDATE addresses SET entity_type = 'contact' WHERE entity_type = 'company'"
    )
    # Rename company_id to contact_id in mails (if column exists)
    conn = op.get_bind()
    if conn.dialect.has_column(conn, "mails", "company_id"):
        op.alter_column("mails", "company_id", new_column_name="contact_id")


def downgrade():
    # Revert entity_links: contact -> company (only for rows that were originally company)
    op.execute(
        "UPDATE entity_links SET entity_type = 'company' WHERE entity_type = 'contact'"
    )
    # Revert tag_assignments: contact -> company
    op.execute(
        "UPDATE tag_assignments SET entity_type = 'company' WHERE entity_type = 'contact'"
    )
    # Revert calendar_entry_links: contact -> company
    op.execute(
        "UPDATE calendar_entry_links SET entity_type = 'company' WHERE entity_type = 'contact'"
    )
    # Revert addresses: contact -> company
    op.execute(
        "UPDATE addresses SET entity_type = 'company' WHERE entity_type = 'contact'"
    )
    # Rename contact_id back to company_id in mails
    conn = op.get_bind()
    if conn.dialect.has_column(conn, "mails", "contact_id"):
        op.alter_column("mails", "contact_id", new_column_name="company_id")
