"""Seed test invoices for the green-hills dev tenant. Safe to re-run."""
import asyncio, sys, os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy import text
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
from src.core.config import settings


INVOICES = [
    ("INV-2025-001", "paid",    349.00, 349.00,   0.00, "2025-02-01"),
    ("INV-2025-002", "paid",    349.00, 349.00,   0.00, "2025-03-01"),
    ("INV-2025-003", "paid",    349.00, 349.00,   0.00, "2025-04-01"),
    ("INV-2025-004", "paid",    349.00, 349.00,   0.00, "2025-05-01"),
    ("INV-2025-005", "failed",  349.00,   0.00, 349.00, "2025-06-01"),
]


async def main():
    db_url = settings.DATABASE_URL
    if not db_url.startswith("postgresql+psycopg://"):
        db_url = "postgresql+psycopg://" + db_url.split("://", 1)[-1]

    engine = create_async_engine(db_url, echo=False)
    SessionLocal = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

    async with SessionLocal() as db:
        row = (await db.execute(
            text("SELECT id FROM accounts WHERE subdomain = 'green-hills'")
        )).fetchone()
        if not row:
            print("ERROR: green-hills tenant not found. Run seed_dev_data.py first.")
            return

        tid = str(row[0])
        print(f"Tenant id: {tid}")

        for num, status, total, paid, balance, due in INVOICES:
            exists = (await db.execute(
                text("SELECT id FROM invoices WHERE tenant_id = :tid AND invoice_number = :num"),
                {"tid": tid, "num": num},
            )).fetchone()

            if exists:
                print(f"[skip]    {num}")
                continue

            await db.execute(
                text("""
                    INSERT INTO invoices
                        (tenant_id, invoice_number, status, total_amount, paid_amount,
                         balance_due, due_date, purchaser_name, purchaser_email,
                         created_at, updated_at)
                    VALUES
                        (:tid, :num, :status, :total, :paid,
                         :balance, :due, :pname, :pemail,
                         NOW(), NOW())
                """),
                {
                    "tid": tid,
                    "num": num,
                    "status": status,
                    "total": total,
                    "paid": paid,
                    "balance": balance,
                    "due": due,
                    "pname": "Green Hills Cemetery",
                    "pemail": "admin@green-hills.com",
                },
            )
            print(f"[created] {num}  ({status}  ${total:.2f})")

        await db.commit()
        print("\nDone.")

    await engine.dispose()


if __name__ == "__main__":
    asyncio.run(main())
