"""Party creation — the single choke point that keeps the 1:1 subtype
invariant (ADR #012/#013): every org party has an ``organizations`` row,
every person party a ``people`` row. Create parties through these helpers,
never ``Party(...)`` directly, so the detail row is always present and the
subtype kind is correct.

Detail rows start with all fields NULL (legacy carried no org-only or
person-only data). The rebuild-from-legacy transform has its own raw-SQL
equivalent in ``services.migrate.transforms._insert_party``; keep the two
in step.
"""

from __future__ import annotations

from sqlalchemy.orm import Session

from app.models import Organization, Party, Person


def create_org_party(
    session: Session,
    *,
    name: str,
    slug: str,
    email: str | None = None,
    phone: str | None = None,
    address: str | None = None,
    notes: str | None = None,
    is_active: bool = True,
) -> Party:
    """Create an org party and its ``organizations`` detail row (1:1)."""
    party = Party(
        kind="org",
        name=name,
        slug=slug,
        email=email,
        phone=phone,
        address=address,
        notes=notes,
        is_active=is_active,
    )
    session.add(party)
    session.flush()
    session.add(Organization(party_id=party.id))
    session.flush()
    return party


def create_person_party(
    session: Session,
    *,
    name: str,
    slug: str,
    email: str | None = None,
    phone: str | None = None,
    address: str | None = None,
    notes: str | None = None,
    is_active: bool = True,
) -> Party:
    """Create a person party and its ``people`` detail row (1:1)."""
    party = Party(
        kind="person",
        name=name,
        slug=slug,
        email=email,
        phone=phone,
        address=address,
        notes=notes,
        is_active=is_active,
    )
    session.add(party)
    session.flush()
    session.add(Person(party_id=party.id))
    session.flush()
    return party
