from datetime import datetime
from app.models import db, Invoice, User, Plan

def generate_invoice(user_id, plan_id):
    user = User.query.get(user_id)
    plan = Plan.query.get(plan_id)

    # Calculate prices and taxes
    price = plan.price
    qty = 1
    extended_price = price * qty
    subtotal = extended_price
    sales_tax = calculate_sales_tax(user.zip_code, subtotal)  # Implement this function
    total = subtotal + sales_tax
    balance_due = total

    invoice = Invoice(
        customer_id=user.id,
        order_date=datetime.utcnow(),
        shipped_electronically_to=user.email,
        plan_id=plan.id,
        plan_description=plan.features,
        price=price,
        qty=qty,
        extended_price=extended_price,
        subtotal=subtotal,
        sales_tax=sales_tax,
        total=total,
        balance_due=balance_due,
        is_paid=False
    )

    db.session.add(invoice)
    db.session.commit()
    return invoice


def calculate_sales_tax(zip_code, amount):
    # Implement a function to calculate sales tax based on zip code
    # For simplicity, return a fixed rate for now
    tax_rate = 0.07  # Example tax rate
    return amount * tax_rate
