"""T02: contacts, company_contacts, FTS search_tsv on companies.

Revision ID: 0002_contacts_fts
Revises: 0001_initial
Create Date: 2026-06-29
"""

from __future__ import annotations

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

revision: str = "0002_contacts_fts"
down_revision: Union[str, None] = "0001_initial"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # --- companies: add FTS search_tsv computed column ---
    op.execute(
        """
        ALTER TABLE companies
        ADD COLUMN search_tsv TSVECTOR
        GENERATED ALWAYS AS (
            to_tsvector('english',
                coalesce(name, '') || ' ' ||
                coalesce(description, '') || ' ' ||
                coalesce(industry, '')
            )
        ) STORED
        """
    )
    op.create_index(
        "ix_companies_search_vec",
        "companies",
        ["search_tsv"],
        postgresql_using="gin",
    )
    op.create_index(
        "ix_companies_industry",
        "companies",
        ["tenant_id", "industry"],
    )

    # --- contacts ---
    op.create_table(
        "contacts",
        sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
        sa.Column("tenant_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False),
        sa.Column("first_name", sa.String(100), nullable=False),
        sa.Column("last_name", sa.String(100), nullable=False),
        sa.Column("email", sa.String(255), nullable=True),
        sa.Column("phone", sa.String(30), nullable=True),
        sa.Column("mobile", sa.String(30), nullable=True),
        sa.Column("position", sa.String(100), nullable=True),
        sa.Column("department", sa.String(100), nullable=True),
        sa.Column("linkedin_url", sa.String(500), nullable=True),
        sa.Column("notes", sa.Text, nullable=True),
        sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("created_by", postgresql.UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="SET NULL"), nullable=True),
        sa.Column("updated_by", postgresql.UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="SET NULL"), nullable=True),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
        sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
    )
    op.create_index("ix_contacts_tenant_id", "contacts", ["tenant_id"])
    op.create_index("ix_contacts_tenant_deleted", "contacts", ["tenant_id", "deleted_at"])
    op.create_index("ix_contacts_tenant_name", "contacts", ["tenant_id", "last_name", "first_name"])
    op.create_index("ix_contacts_email", "contacts", ["email"])

    # --- company_contacts (N:M join) ---
    op.create_table(
        "company_contacts",
        sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
        sa.Column("tenant_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False),
        sa.Column("company_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("companies.id", ondelete="CASCADE"), nullable=False),
        sa.Column("contact_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("contacts.id", ondelete="CASCADE"), nullable=False),
        sa.Column("role_at_company", sa.String(100), nullable=True),
        sa.Column("is_primary", sa.Boolean, nullable=False, server_default=sa.text("false")),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
        sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
        sa.UniqueConstraint("company_id", "contact_id", "tenant_id", name="uq_company_contact_tenant"),
    )
    op.create_index("ix_cc_company", "company_contacts", ["company_id"])
    op.create_index("ix_cc_contact", "company_contacts", ["contact_id"])
    op.create_index("ix_company_contacts_tenant_id", "company_contacts", ["tenant_id"])

    # --- RLS on new tenant-scoped tables ---
    for table in ["contacts", "company_contacts"]:
        op.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")
        op.execute(
            f"""CREATE POLICY tenant_isolation ON {table}
            USING (tenant_id = current_setting('app.current_tenant_id')::uuid)"""
        )


def downgrade() -> None:
    op.drop_table("company_contacts")
    op.drop_table("contacts")
    op.drop_index("ix_companies_search_vec", table_name="companies")
    op.drop_index("ix_companies_industry", table_name="companies")
    op.execute("ALTER TABLE companies DROP COLUMN search_tsv")
