from datetime import datetime
from sqlalchemy import extract

from app.models import Invoice


def generate_invoice_number(company_branch):
    now = datetime.now()

    fy_short = str(now.year)[-2:]
    month = now.month

    branch_code = (company_branch.branch_code or "GEN").upper()

    count = (
        Invoice.query
        .filter(
            Invoice.company_branch_id == company_branch.id,
            extract('year', Invoice.created_at) == now.year
        )
        .count()
    ) + 1

    return f"CN/{branch_code}/{fy_short}/{month}/{count}"