"""People + Organizations subtype tables over the party supertype, plus
party_affiliations (ADR #012/#013).

parties stays the identity anchor carrying the COMMON identity every actor
has (name, slug, contact, kind). This migration adds detail tables only
for the fields that DIFFER by kind — organizations (billing currency + the
Drive/Mosiah folder refs the suite satellites read) and people (the
first-class growth home) — plus party_affiliations, the
person<->organization relationship graph (owner-of, employee-of, contact,
cc).

ADDITIVE ONLY: no column moves off parties, so every existing read
(the diff harness, reporting, the resolver) is untouched and the harness
stays green by construction. Detail + affiliation FKs cascade on party
delete so the rebuild-from-legacy transform's DELETE FROM parties stays
clean without adding these to its TRUNCATE list.

Backfill: one organizations row per org party, one people row per person
party (the 1:1 invariant). affiliations start empty (no legacy source).

Revision ID: 0006
Revises: 0005
Create Date: 2026-07-10
"""

from collections.abc import Sequence

import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

from alembic import op

revision: str = "0006"
down_revision: str | None = "0005"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def _created_at() -> sa.Column:
    return sa.Column(
        "created_at",
        sa.DateTime(timezone=True),
        nullable=False,
        server_default=sa.text("now()"),
    )


def _updated_at() -> sa.Column:
    return sa.Column(
        "updated_at",
        sa.DateTime(timezone=True),
        nullable=False,
        server_default=sa.text("now()"),
    )


def _party_fk(name: str) -> sa.Column:
    return sa.Column(
        name,
        postgresql.UUID(as_uuid=True),
        sa.ForeignKey("parties.id", ondelete="CASCADE"),
        nullable=False,
    )


def upgrade() -> None:
    # --- organizations (org-only detail; 1:1 with an org party) ----------
    op.create_table(
        "organizations",
        sa.Column(
            "party_id",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("parties.id", ondelete="CASCADE"),
            primary_key=True,
        ),
        sa.Column("legal_name", sa.Text(), nullable=True),
        sa.Column("currency", sa.CHAR(3), nullable=True),
        sa.Column("drive_folder_url", sa.Text(), nullable=True),
        sa.Column("mosiah_folder", sa.Text(), nullable=True),
        _created_at(),
        _updated_at(),
    )

    # --- people (person-only detail; 1:1 with a person party) ------------
    op.create_table(
        "people",
        sa.Column(
            "party_id",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("parties.id", ondelete="CASCADE"),
            primary_key=True,
        ),
        _created_at(),
        _updated_at(),
    )

    # --- party_affiliations (person <-> organization relationship graph) --
    op.create_table(
        "party_affiliations",
        sa.Column(
            "id",
            postgresql.UUID(as_uuid=True),
            primary_key=True,
            server_default=sa.text("gen_random_uuid()"),
        ),
        _party_fk("person_party_id"),
        _party_fk("org_party_id"),
        sa.Column("role", sa.Text(), nullable=False),
        sa.Column("title", sa.Text(), nullable=True),
        sa.Column("started_on", sa.Date(), nullable=True),
        sa.Column("ended_on", sa.Date(), nullable=True),
        sa.Column("notes", sa.Text(), nullable=True),
        _created_at(),
        _updated_at(),
        sa.CheckConstraint(
            "role IN ('owner', 'employee', 'contractor', 'contact',"
            " 'billing_contact', 'cc_recipient', 'member', 'other')",
            name="ck_party_affiliations_role",
        ),
        sa.CheckConstraint(
            "person_party_id <> org_party_id", name="ck_party_affiliations_distinct"
        ),
    )
    op.create_index(
        "ix_party_affiliations_person", "party_affiliations", ["person_party_id"]
    )
    op.create_index(
        "ix_party_affiliations_org", "party_affiliations", ["org_party_id"]
    )
    # At most one ACTIVE affiliation per (person, org, role).
    op.create_index(
        "uq_party_affiliations_active",
        "party_affiliations",
        ["person_party_id", "org_party_id", "role"],
        unique=True,
        postgresql_where=sa.text("ended_on IS NULL"),
    )

    # --- backfill the 1:1 detail rows for existing parties ----------------
    op.execute(
        "INSERT INTO organizations (party_id) SELECT id FROM parties WHERE kind = 'org'"
    )
    op.execute(
        "INSERT INTO people (party_id) SELECT id FROM parties WHERE kind = 'person'"
    )


def downgrade() -> None:
    op.drop_table("party_affiliations")
    op.drop_table("people")
    op.drop_table("organizations")
