"""
The contract_signed email context built plot_id/section straight from
Contract.plot_id (a raw UUID FK) and a nonexistent Contract.section
attribute — so purchasers saw a raw UUID ("for 30e228ef-f5fa-... in —")
instead of a human-readable plot reference and section name.
"""
from __future__ import annotations

import pytest
from sqlalchemy.ext.asyncio import AsyncSession

from src.apps.plots.models.plot import Plot
from src.apps.sections.models.section import Section
from src.worker.arq_app import resolve_plot_and_section_labels


async def _make_section(db, account, code="A", name="Section A") -> Section:
    sec = Section(tenant_id=account.id, code=code, name=name)
    db.add(sec)
    await db.flush()
    return sec


async def _make_plot(db, account, section, ref="A-1") -> Plot:
    plot = Plot(tenant_id=account.id, plot_ref=ref, section_id=section.id, status="reserved")
    db.add(plot)
    await db.flush()
    return plot


@pytest.mark.asyncio
async def test_resolves_plot_ref_and_section_name_from_ids(
    db_session: AsyncSession, test_account,
):
    section = await _make_section(db_session, test_account)
    plot = await _make_plot(db_session, test_account, section)

    plot_label, section_label = await resolve_plot_and_section_labels(
        db_session, test_account.id, plot.id, section.id
    )
    assert plot_label == "A-1"
    assert section_label == "Section A"


@pytest.mark.asyncio
async def test_falls_back_to_plots_own_section_when_contract_section_id_unset(
    db_session: AsyncSession, test_account,
):
    """Mirrors the real Sardar-family contract: plot_id set, section_id not."""
    section = await _make_section(db_session, test_account)
    plot = await _make_plot(db_session, test_account, section)

    plot_label, section_label = await resolve_plot_and_section_labels(
        db_session, test_account.id, plot.id, None
    )
    assert plot_label == "A-1"
    assert section_label == "Section A"


@pytest.mark.asyncio
async def test_returns_empty_strings_when_no_plot_or_section(
    db_session: AsyncSession, test_account,
):
    plot_label, section_label = await resolve_plot_and_section_labels(
        db_session, test_account.id, None, None
    )
    assert plot_label == ""
    assert section_label == ""
