"""Endpoint de sincronizacion de ventas offline."""
import json
from datetime import datetime
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session as DBSession
from database import get_db
from models import Session, AuditLog, SyncQueue
from schemas import SyncUploadRequest, SyncUploadResponse

router = APIRouter(prefix="/api/sync", tags=["Sync"])


@router.post("/upload", response_model=SyncUploadResponse)
def upload_offline_sales(req: SyncUploadRequest, db: DBSession = Depends(get_db)):
    """
    Recibe un lote de ventas realizadas offline por una estacion.
    Inserta las nuevas, ignora duplicados (por session_id).
    """
    inserted = 0
    duplicates = 0
    errors = 0

    for sale in req.sales:
        try:
            # Verificar si ya existe (idempotente)
            existing = db.query(Session).filter(Session.id == sale.session_id).first()
            if existing:
                duplicates += 1
                continue

            # Parsear timestamps
            programmed_at = None
            if sale.programmed_at:
                programmed_at = datetime.fromisoformat(sale.programmed_at)

            created_at = None
            if sale.created_at:
                created_at = datetime.fromisoformat(sale.created_at)

            # Insertar sesion
            session = Session(
                id=sale.session_id,
                package_id=sale.package_id,
                status='active' if programmed_at else 'pending',
                red_minutes=sale.red_minutes,
                green_minutes=sale.green_minutes,
                blue_minutes=sale.blue_minutes,
                payment_method=sale.payment_method,
                amount=sale.amount,
                cashier=sale.cashier,
                agent_id=sale.agent_id or req.agent_id,
                programmed_at=programmed_at,
            )
            db.add(session)

            # Auditoria
            db.add(AuditLog(
                action='offline_sync',
                session_id=sale.session_id,
                details=json.dumps({
                    'package': sale.package_id,
                    'amount': sale.amount,
                    'agent_id': sale.agent_id or req.agent_id,
                    'original_created_at': sale.created_at,
                }),
                cashier=sale.cashier,
            ))

            # Cola de sync a cloud
            db.add(SyncQueue(
                table_name='sessions',
                record_id=sale.session_id,
                action='insert',
                payload=json.dumps({
                    'id': sale.session_id,
                    'package_id': sale.package_id,
                    'amount': sale.amount,
                    'payment_method': sale.payment_method,
                    'programmed_at': sale.programmed_at,
                    'source': 'offline_sync',
                }),
            ))

            inserted += 1
        except Exception as e:
            errors += 1
            print(f"[Sync] Error procesando venta {sale.session_id}: {e}")

    if inserted > 0 or errors == 0:
        db.commit()

    print(f"[Sync] Agent {req.agent_id}: {inserted} insertadas, {duplicates} duplicadas, {errors} errores")

    return SyncUploadResponse(
        status="ok",
        accepted=inserted,
    )
