from fastapi import APIRouter
from fastapi.responses import StreamingResponse
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from models import Fatura
from database import AsyncSessionLocal
import pandas as pd
from io import BytesIO

router = APIRouter()

@router.get("/export-excel")
async def exportar_excel():
    async with AsyncSessionLocal() as session:
        result = await session.execute(select(Fatura))
        faturas = result.scalars().all()

        # Converte os objetos para lista de dicionários
        data = [f.__dict__ for f in faturas]
        for row in data:
            row.pop('_sa_instance_state', None)  # remove campo interno do SQLAlchemy

        df = pd.DataFrame(data)

        # Converte para Excel em memória
        buffer = BytesIO()
        with pd.ExcelWriter(buffer, engine='xlsxwriter') as writer:
            df.to_excel(writer, index=False, sheet_name='Faturas')

        buffer.seek(0)
        return StreamingResponse(buffer, media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                                 headers={"Content-Disposition": "attachment; filename=faturas.xlsx"})
