"""A form field holding another record's id (link_source — e.g. a Hidden
application_id on a "forward" form) lets pages read that record's fields as
lookup columns ("application_id.applicant_name"); the field keeps its raw id."""

import uuid

import pytest
from pydantic import ValidationError

from app.schemas.workflow import FormFieldDef


async def _published(client, headers, name, fields):
    resp = await client.post("/forms", headers=headers, json={"name": f"{name} {uuid.uuid4().hex[:6]}", "field_definitions": fields})
    assert resp.status_code == 201, resp.text
    return (await client.post(f"/forms/{resp.json()['form_id']}/publish", headers=headers)).json()


async def _submit(client, headers, form, values):
    resp = await client.post("/form-submissions", headers=headers, json={"form_id": form["form_id"], "form_version": form["version"], "field_values": values})
    assert resp.status_code == 201, resp.text
    return resp.json()


async def test_lookup_columns_through_a_hidden_link(client, auth_headers):
    application = await _published(client, auth_headers, "Application", [{"name": "applicant_name", "type": "text", "label": "Applicant"}, {"name": "number", "type": "text", "label": "No."}])
    forward = await _published(
        client,
        auth_headers,
        "Forward",
        [
            {"name": "note", "type": "text", "label": "Note"},
            {"name": "application_id", "type": "hidden", "label": "Application", "link_source": f"form:{application['form_id']}", "link_display_field": "number"},
        ],
    )
    app_sub = await _submit(client, auth_headers, application, {"applicant_name": "Asha", "number": "RTI/1"})
    await _submit(client, auth_headers, forward, {"note": "Please draft", "application_id": app_sub["id"]})

    rows = (
        await client.post(
            "/datasets/query",
            headers=auth_headers,
            json={"source_type": "form", "source_id": forward["form_id"], "columns": ["note", "application_id", "application_id.applicant_name", "application_id.number"]},
        )
    ).json()["rows"]
    assert rows[0]["application_id.applicant_name"] == "Asha"
    assert rows[0]["application_id.number"] == "RTI/1"
    assert rows[0]["application_id"] == app_sub["id"]


def test_only_id_holding_fields_link():
    FormFieldDef(name="a", type="text", label="A", link_source=f"master:{uuid.uuid4()}")
    with pytest.raises(ValidationError):
        FormFieldDef(name="a", type="number", label="A", link_source=f"form:{uuid.uuid4()}")
    with pytest.raises(ValidationError):
        FormFieldDef(name="a", type="hidden", label="A", link_source="form:not-an-id")
    with pytest.raises(ValidationError):
        FormFieldDef(name="a", type="hidden", label="A", link_display_field="number")
