"""Entity-manage tests ride the entries_write graph (same seeded
business slice) plus per-test extensions for the merge matrix."""

from datetime import datetime

from sqlalchemy import select

from app.models import Engagement, Party, Project, TimeEntry
from tests.entries_write.conftest import (  # noqa: F401  (shared fixtures)
    actor_for,
    adi,
    g,
    gary,
    rian,
)


def add_client(graph, operator, name: str, slug: str) -> Party:
    """A fresh client party + active direct_client edge under operator."""
    party = Party(kind="org", name=name, slug=slug)
    graph.session.add(party)
    graph.session.flush()
    graph.session.add(
        Engagement(
            tenant_id=graph.tenant.id, type="direct_client",
            party_a_id=operator.id, party_b_id=party.id,
            role_a="operator", role_b="client",
        )
    )
    graph.session.flush()
    return party


def add_project(graph, operator, client, name: str) -> Project:
    project = Project(
        tenant_id=graph.tenant.id, operator_party_id=operator.id,
        client_party_id=client.id, name=name, status="active",
    )
    graph.session.add(project)
    graph.session.flush()
    return project


def add_entry(graph, project, description: str, **kw) -> TimeEntry:
    defaults = dict(
        tenant_id=graph.tenant.id, source="clockify",
        import_id=graph.batches["adi"].id,
        start_at=datetime(2026, 6, 5, 9, 0, 0),
        end_at=datetime(2026, 6, 5, 10, 0, 0),
        duration_seconds=3600, billable=True,
        project_id=project.id if project else None,
        description=description,
    )
    defaults.update(kw)
    entry = TimeEntry(**defaults)
    graph.session.add(entry)
    graph.session.flush()
    return entry


def entry_project_ids(graph, *entries):
    ids = [e.id for e in entries]
    rows = graph.session.execute(
        select(TimeEntry.id, TimeEntry.project_id).where(TimeEntry.id.in_(ids))
    ).all()
    return {row[0]: row[1] for row in rows}
