# app/services/invoice_service.py
import logging
from datetime import date
from fastapi import BackgroundTasks
from pymongo.collection import Collection
from ...models.saas.invoices import SaaSInvoiceCreate, SaaSInvoiceDB, SaaSInvoiceUpdate
from ...models.common import InvoiceStatus
from ....db import database
# from ...libraries.email_templates import (
#     invoice_created_email,
#     send_invoice_paid_email,
#     send_invoice_reminder_email
# )

logger = logging.getLogger(__name__)

INVOICE_COLLECTION = "saas_invoices"

async def create_invoice_service(
    invoice_in: SaaSInvoiceCreate,
    db: database.MongoDB,
    background_tasks: BackgroundTasks
) -> SaaSInvoiceDB:
    coll: Collection = db[INVOICE_COLLECTION]
    data = invoice_in.dict()
    result = coll.insert_one(data)
    invoice_id = str(result.inserted_id)

    # schedule email
    background_tasks.add_task(
        send_invoice_created_email,
        invoice_id=invoice_id,
        to_account=invoice_in.account_id,
        title=invoice_in.invoice_title,
        amount=invoice_in.amount,
        due_date=invoice_in.due_date
    )
    return SaaSInvoiceDB(**data, invoice_id=invoice_id)

async def list_invoices_service(
    db: database.MongoDB, account_id: str = None
) -> list[SaaSInvoiceDB]:
    coll: Collection = db[INVOICE_COLLECTION]
    query = {"account_id": account_id} if account_id else {}
    docs = list(coll.find(query).sort("invoice_date", -1))
    return [SaaSInvoiceDB(**doc, invoice_id=str(doc["_id"])) for doc in docs]

async def get_invoice_service(
    invoice_id: str, db: database.MongoDB
) -> SaaSInvoiceDB:
    coll: Collection = db[INVOICE_COLLECTION]
    doc = coll.find_one({"_id": database.str_to_objectid(invoice_id)})
    if not doc:
        raise ValueError("Invoice not found")
    return SaaSInvoiceDB(**doc, invoice_id=str(doc["_id"]))

async def update_invoice_status_service(
    invoice_id: str,
    update: SaaSInvoiceUpdate,
    db: database.MongoDB,
    background_tasks: BackgroundTasks
) -> SaaSInvoiceDB:
    coll: Collection = db[INVOICE_COLLECTION]
    coll.update_one(
        {"_id": database.str_to_objectid(invoice_id)},
        {"$set": {"status": update.status}}
    )
    updated = coll.find_one({"_id": database.str_to_objectid(invoice_id)})
    invoice = SaaSInvoiceDB(**updated, invoice_id=invoice_id)

    if update.status == InvoiceStatus.PAID:
        background_tasks.add_task(
            send_invoice_paid_email,
            invoice_id=invoice_id,
            to_account=invoice.account_id,
            amount=invoice.amount
        )
    return invoice

async def run_due_reminders(db: database.MongoDB, background_tasks: BackgroundTasks):
    """Mark overdue + send reminders for upcoming due dates."""
    coll: Collection = db[INVOICE_COLLECTION]
    today = date.today()
    # mark overdue
    coll.update_many(
        {"due_date": {"$lt": today}, "status": {"$ne": InvoiceStatus.PAID}},
        {"$set": {"status": InvoiceStatus.OVERDUE}}
    )
    # find due tomorrow
    tomorrow = today
    cursor = coll.find({"due_date": tomorrow, "status": {"$ne": InvoiceStatus.PAID}})
    for doc in cursor:
        invoice_id = str(doc["_id"])
        background_tasks.add_task(
            send_invoice_reminder_email,
            invoice_id=invoice_id,
            to_account=doc["account_id"],
            due_date=doc["due_date"]
        )
