"""Replace the {{payment_url}} paragraph in the seeded contract_signed email
template with a {{bank_details_block}} paragraph (INDL-XX Bank Details Settings).

ContractIssueService's payment-link flow is being replaced by a Payment
Details + Bank Details block (rendered server-side in worker/arq_app.py's
send_contract_email into context["bank_details_block"]) — the template body
no longer references {{payment_url}} directly.

Two variants of the seeded body currently exist in production, split by when
the tenant was provisioned:

  Variant A — tenants provisioned via/after migration 0072, before a later,
  migration-less edit to SYSTEM_TEMPLATES added {{payment_summary}}. Body
  contains the literal line "Balance due: {{balance_due}}".

  Variant B — tenants provisioned against the CURRENT
  src/apps/settings/services/email_template_service.py:SYSTEM_TEMPLATES
  source (no migration ever seeded this variant — EmailTemplateService.
  seed_system_templates() reads SYSTEM_TEMPLATES live at provisioning time,
  so any tenant created after that source edit already has this body without
  any migration involved). Body contains "{{payment_summary}}" in place of
  the "Balance due" line.

Both variants get the same surgical change: the
"To complete your payment online, visit:\n{{payment_url}}\n\n" paragraph is
replaced with "{{bank_details_block}}\n\n". Neither variant's
balance_due/payment_summary divergence is touched here — that is a
pre-existing, unrelated drift, out of scope for this migration.

Only updates rows whose body still exactly matches one of the two known
seeded defaults — a tenant that has customized their contract_signed
template via Settings is left untouched, same guard as 0072/0077.

NOTE: migrations are self-contained/frozen-in-time — this file keeps its own
copy of the old/new body text. It intentionally mirrors the change that must
also be made to
src/apps/settings/services/email_template_service.py:SYSTEM_TEMPLATES
(Variant B's body is the one the source dict should adopt going forward).

Revision ID: 0079
Revises: 0078
"""
import json

import sqlalchemy as sa
from alembic import op

revision = "0079"
down_revision = "0078"
branch_labels = None
depends_on = None

# ---------------------------------------------------------------------------
# Variant A — matches 0072's seeded output exactly (pre-payment_summary-drift
# tenants).
# ---------------------------------------------------------------------------
OLD_BODY_A = (
    "Dear {{purchaser_name}},\n\n"
    "Thank you for choosing {{cemetery_name}}. This confirms your "
    "{{contract_type}} contract ({{contract_number}}) for {{plot_id}} "
    "in {{section}} has been signed.\n\n"
    "Contract total: {{contract_total}}\n"
    "Balance due: {{balance_due}}\n\n"
    "To complete your payment online, visit:\n{{payment_url}}\n\n"
    "If you have any questions, contact us at {{cemetery_email}} or "
    "{{cemetery_phone}}.\n\n"
    "Sincerely,\n{{cemetery_name}}"
)
NEW_BODY_A = (
    "Dear {{purchaser_name}},\n\n"
    "Thank you for choosing {{cemetery_name}}. This confirms your "
    "{{contract_type}} contract ({{contract_number}}) for {{plot_id}} "
    "in {{section}} has been signed.\n\n"
    "Contract total: {{contract_total}}\n"
    "Balance due: {{balance_due}}\n\n"
    "{{bank_details_block}}\n\n"
    "If you have any questions, contact us at {{cemetery_email}} or "
    "{{cemetery_phone}}.\n\n"
    "Sincerely,\n{{cemetery_name}}"
)
MERGE_FIELDS_A_OLD = [
    "purchaser_name", "contract_type", "plot_id", "section",
    "contract_number", "contract_total", "balance_due", "payment_url",
    "cemetery_name", "cemetery_email", "cemetery_phone", "current_date",
]
MERGE_FIELDS_A_NEW = [
    "purchaser_name", "contract_type", "plot_id", "section",
    "contract_number", "contract_total", "balance_due", "bank_details_block",
    "cemetery_name", "cemetery_email", "cemetery_phone", "current_date",
]

# ---------------------------------------------------------------------------
# Variant B — matches the CURRENT SYSTEM_TEMPLATES source body (post-
# payment_summary-drift tenants; also what new signups get today).
# ---------------------------------------------------------------------------
OLD_BODY_B = (
    "Dear {{purchaser_name}},\n\n"
    "Thank you for choosing {{cemetery_name}}. This confirms your "
    "{{contract_type}} contract ({{contract_number}}) for {{plot_id}} "
    "in {{section}} has been signed.\n\n"
    "Contract total: {{contract_total}}\n"
    "{{payment_summary}}\n\n"
    "To complete your payment online, visit:\n{{payment_url}}\n\n"
    "If you have any questions, contact us at {{cemetery_email}} or "
    "{{cemetery_phone}}.\n\n"
    "Sincerely,\n{{cemetery_name}}"
)
NEW_BODY_B = (
    "Dear {{purchaser_name}},\n\n"
    "Thank you for choosing {{cemetery_name}}. This confirms your "
    "{{contract_type}} contract ({{contract_number}}) for {{plot_id}} "
    "in {{section}} has been signed.\n\n"
    "Contract total: {{contract_total}}\n"
    "{{payment_summary}}\n\n"
    "{{bank_details_block}}\n\n"
    "If you have any questions, contact us at {{cemetery_email}} or "
    "{{cemetery_phone}}.\n\n"
    "Sincerely,\n{{cemetery_name}}"
)
MERGE_FIELDS_B_OLD = [
    "purchaser_name", "contract_type", "plot_id", "section",
    "contract_number", "contract_total", "payment_summary", "payment_url",
    "cemetery_name", "cemetery_email", "cemetery_phone", "current_date",
]
MERGE_FIELDS_B_NEW = [
    "purchaser_name", "contract_type", "plot_id", "section",
    "contract_number", "contract_total", "payment_summary", "bank_details_block",
    "cemetery_name", "cemetery_email", "cemetery_phone", "current_date",
]

VARIANTS = [
    (OLD_BODY_A, NEW_BODY_A, MERGE_FIELDS_A_OLD, MERGE_FIELDS_A_NEW),
    (OLD_BODY_B, NEW_BODY_B, MERGE_FIELDS_B_OLD, MERGE_FIELDS_B_NEW),
]


def upgrade() -> None:
    conn = op.get_bind()
    for old_body, new_body, _old_fields, new_fields in VARIANTS:
        conn.execute(
            sa.text(
                """
                UPDATE email_templates
                SET body = :new_body,
                    merge_fields = CAST(:merge_fields AS JSONB),
                    updated_at = now()
                WHERE template_key = 'contract_signed'
                  AND is_system = true
                  AND body = :old_body
                """
            ),
            {
                "new_body": new_body,
                "old_body": old_body,
                "merge_fields": json.dumps(new_fields),
            },
        )


def downgrade() -> None:
    """Best-effort revert: only rows still exactly on one of the new bodies."""
    conn = op.get_bind()
    for old_body, new_body, old_fields, _new_fields in VARIANTS:
        conn.execute(
            sa.text(
                """
                UPDATE email_templates
                SET body = :old_body,
                    merge_fields = CAST(:merge_fields AS JSONB),
                    updated_at = now()
                WHERE template_key = 'contract_signed'
                  AND is_system = true
                  AND body = :new_body
                """
            ),
            {
                "old_body": old_body,
                "new_body": new_body,
                "merge_fields": json.dumps(old_fields),
            },
        )
