"""Marketing FAQ Section CMS (INDL-52)

Revision ID: 0059
Revises: 0058
Create Date: 2026-07-03

Adds platform-level (non-tenant) tables backing the public marketing
website's Home page FAQ section, alongside the existing `cms_pages` and
`blog_posts` tables:

- `faq_section_settings` — singleton row holding the section-level copy
  (heading / subheading / intro).
- `faq_items` — ordered, soft-deletable list of question/answer pairs.

Seeds one settings row and the 7 FAQ items currently hard-coded in
indelis-frontend's MarketingHomePage.tsx (lines ~647-724), copied verbatim
so post-migration content matches pre-migration content exactly (AC-14).

All seeded text is passed via SQLAlchemy `text()` bindparams — never
f-string/percent interpolated — to avoid quoting issues and SQL injection
in the migration itself.

NOTE: chains off "0058b" (formerly-mis-numbered "0058" / pg_trgm_extension,
renumbered as part of this migration to resolve a pre-existing revision-id
collision — see 0058_pg_trgm_extension.py and 0057_memorial_public_page_fields.py
for details), which is the true single head as of this change.
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

revision = "0059"
down_revision = "0058b"
branch_labels = None
depends_on = None


FAQ_ITEMS = [
    {
        "question": (
            "How long does it take to move our records over from paper or "
            "our old system?"
        ),
        "answer": (
            "Most cemeteries are up and running in 4–6 weeks. Our team does "
            "the hard part — scanning paper ledgers, tidying up "
            "spreadsheets, and bringing your records in for you so you can "
            "check them before they go live. Larger archives may take a bit "
            "longer; we'll give you a clear timeline after a first call."
        ),
    },
    {
        "question": "Where is our data stored, and who can see it?",
        "answer": (
            "All your records are stored on secure servers in Canada, "
            "encrypted both in storage and while moving over the internet. "
            "Each staff member only sees the parts they need to, every "
            "change is logged, and we sign a written privacy agreement that "
            "meets Canadian privacy law. Your data belongs to you — you can "
            "export everything any time."
        ),
    },
    {
        "question": "Do we have to use the AI features?",
        "answer": (
            "No. The AI helpers (reading headstones, drafting life stories, "
            "plain-English search for families) are all optional — you can "
            "turn them off completely. When they are on, they only suggest; "
            "a real person always reviews and edits before anything is "
            "saved or published."
        ),
    },
    {
        "question": "Can families pay online?",
        "answer": (
            "Yes. Families can pay by credit card online, set up a payment "
            "plan, or pay through a link you email them. Cash, cheque, and "
            "bank transfers can be recorded by your office, and INDELIS "
            "sends automatic reminders for overdue invoices at 7, 14, and "
            "30 days."
        ),
    },
    {
        "question": "What about training and ongoing support?",
        "answer": (
            "Every cemetery gets live training tailored to each role — "
            "office staff, sales, and grounds crews — plus walk-throughs "
            "during the first few weeks. Ongoing support is included in "
            "every plan, with extra service-level options for larger "
            "municipal and multi-site customers."
        ),
    },
    {
        "question": "Can we host INDELIS on our own servers?",
        "answer": (
            "Yes. The default — and what we recommend — is for us to host "
            "and maintain it for you, with your data in Canada. For "
            "councils that need it on their own servers, we offer that too "
            "under the same terms. Just ask and we'll walk you through it."
        ),
    },
    {
        "question": "How is pricing structured?",
        "answer": (
            "Pricing is based on the size of your cemetery (number of "
            "plots) and the parts of INDELIS you turn on. Simple annual "
            "plans, no per-user fees, no surprises. See our pricing page or "
            "ask us for a quote tailored to your cemetery."
        ),
    },
]

SETTINGS_HEADING = "Answers for the questions cemetery teams actually ask"
SETTINGS_SUBHEADING = "Frequently asked"


def upgrade() -> None:
    conn = op.get_bind()

    op.create_table(
        "faq_section_settings",
        sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True,
                  server_default=sa.text("gen_random_uuid()")),
        sa.Column("heading", sa.String(200), nullable=False),
        sa.Column("subheading", sa.String(300), nullable=True),
        sa.Column("intro", sa.Text, nullable=True),
        sa.Column("created_at", sa.DateTime(timezone=True),
                  server_default=sa.text("now()"), nullable=False),
        sa.Column("updated_at", sa.DateTime(timezone=True),
                  server_default=sa.text("now()"), nullable=False),
    )

    op.create_table(
        "faq_items",
        sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True,
                  server_default=sa.text("gen_random_uuid()")),
        sa.Column("question", sa.String(300), nullable=False),
        sa.Column("answer", sa.Text, nullable=False),
        sa.Column("sort_order", sa.Integer, nullable=False, server_default="0"),
        sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("created_at", sa.DateTime(timezone=True),
                  server_default=sa.text("now()"), nullable=False),
        sa.Column("updated_at", sa.DateTime(timezone=True),
                  server_default=sa.text("now()"), nullable=False),
    )
    op.create_index("ix_faq_items_sort_order", "faq_items", ["sort_order"])
    op.create_index("ix_faq_items_deleted_at", "faq_items", ["deleted_at"])

    # ── Seed the singleton settings row ──────────────────────────────────────
    conn.execute(
        sa.text(
            """
            INSERT INTO faq_section_settings (id, heading, subheading, intro, created_at, updated_at)
            VALUES (gen_random_uuid(), :heading, :subheading, NULL, now(), now())
            """
        ),
        {"heading": SETTINGS_HEADING, "subheading": SETTINGS_SUBHEADING},
    )

    # ── Seed the 7 FAQ items, preserving current marketing site copy ────────
    insert_item = sa.text(
        """
        INSERT INTO faq_items (id, question, answer, sort_order, created_at, updated_at)
        VALUES (gen_random_uuid(), :question, :answer, :sort_order, now(), now())
        """
    )
    for sort_order, item in enumerate(FAQ_ITEMS):
        conn.execute(
            insert_item,
            {
                "question": item["question"],
                "answer": item["answer"],
                "sort_order": sort_order,
            },
        )


def downgrade() -> None:
    op.drop_table("faq_items")
    op.drop_table("faq_section_settings")
