"""
Modèles pour les recharges TIM BUSINESS
Gestion des commissions 10% (4% TIM BUSINESS + 6% TIM CASH)
"""

from sqlalchemy import Column, String, Integer, Float, DateTime, Enum as SQLEnum, ForeignKey, Text
from sqlalchemy.orm import relationship
from datetime import datetime
import enum
from database import Base


class RechargeStatus(str, enum.Enum):
    """Statut d'une recharge"""
    PENDING = "pending"           # En attente
    PROCESSING = "processing"     # En cours de traitement
    COMPLETED = "completed"       # Complétée avec succès
    FAILED = "failed"            # Échouée
    CANCELLED = "cancelled"       # Annulée
    REFUNDED = "refunded"        # Remboursée


class CommissionType(str, enum.Enum):
    """Type de commission"""
    TIM_BUSINESS = "tim_business"  # Commission pour le compte TIM BUSINESS
    TIM_CASH = "tim_cash"          # Commission pour l'entreprise TIM CASH


class TIMBusinessRecharge(Base):
    """
    Recharge effectuée par un compte TIM BUSINESS
    vers un compte TIM MINI ou TIM MAXI
    """
    __tablename__ = "tim_business_recharges"

    id = Column(String(50), primary_key=True)
    
    # Informations du rechargeur (TIM BUSINESS)
    business_user_id = Column(String(50), ForeignKey("users.id"), nullable=False)
    business_account_type = Column(String(20), default="TIM_BUSINESS")
    
    # Informations du bénéficiaire (TIM MINI/MAXI)
    beneficiary_user_id = Column(String(50), ForeignKey("users.id"), nullable=False)
    beneficiary_phone = Column(String(20), nullable=False)
    beneficiary_account_type = Column(String(20), nullable=False)  # TIM_MINI ou TIM_MAXI
    
    # Montants
    amount = Column(Float, nullable=False)  # Montant de la recharge
    total_commission = Column(Float, nullable=False)  # Commission totale (10%)
    business_commission = Column(Float, nullable=False)  # Commission TIM BUSINESS (4%)
    timcash_commission = Column(Float, nullable=False)  # Commission TIM CASH (6%)
    total_amount = Column(Float, nullable=False)  # Montant total débité (amount + total_commission)
    
    # Soldes avant/après
    business_balance_before = Column(Float, nullable=False)
    business_balance_after = Column(Float, nullable=False)
    beneficiary_balance_before = Column(Float, nullable=False)
    beneficiary_balance_after = Column(Float, nullable=False)
    
    # Statut et dates
    status = Column(SQLEnum(RechargeStatus), default=RechargeStatus.PENDING)
    created_at = Column(DateTime, default=datetime.utcnow)
    completed_at = Column(DateTime, nullable=True)
    failed_at = Column(DateTime, nullable=True)
    
    # Informations supplémentaires
    reference = Column(String(100), unique=True, nullable=False)  # Référence unique
    description = Column(Text, nullable=True)
    failure_reason = Column(Text, nullable=True)
    
    # Métadonnées
    ip_address = Column(String(50), nullable=True)
    device_info = Column(Text, nullable=True)
    location = Column(String(100), nullable=True)
    
    # Relations
    business_user = relationship("User", foreign_keys=[business_user_id])
    beneficiary_user = relationship("User", foreign_keys=[beneficiary_user_id])
    commissions = relationship("RechargeCommission", back_populates="recharge", cascade="all, delete-orphan")
    
    def __repr__(self):
        return f"<TIMBusinessRecharge {self.reference}: {self.amount} FCFA>"


class RechargeCommission(Base):
    """
    Détail des commissions d'une recharge
    Permet de tracer la répartition des commissions
    """
    __tablename__ = "recharge_commissions"

    id = Column(String(50), primary_key=True)
    recharge_id = Column(String(50), ForeignKey("tim_business_recharges.id"), nullable=False)
    
    # Type de commission
    commission_type = Column(SQLEnum(CommissionType), nullable=False)
    
    # Bénéficiaire de la commission
    recipient_user_id = Column(String(50), nullable=True)  # NULL pour TIM CASH
    recipient_type = Column(String(20), nullable=False)  # "tim_business" ou "tim_cash"
    
    # Montant
    amount = Column(Float, nullable=False)
    percentage = Column(Float, nullable=False)  # 4% ou 6%
    
    # Statut
    status = Column(String(20), default="pending")  # pending, credited, failed
    credited_at = Column(DateTime, nullable=True)
    
    # Métadonnées
    created_at = Column(DateTime, default=datetime.utcnow)
    notes = Column(Text, nullable=True)
    
    # Relations
    recharge = relationship("TIMBusinessRecharge", back_populates="commissions")
    
    def __repr__(self):
        return f"<RechargeCommission {self.commission_type}: {self.amount} FCFA>"


class TIMCashCompanyAccount(Base):
    """
    Compte de l'entreprise TIM CASH
    Reçoit les 6% de commission sur les recharges TIM BUSINESS
    """
    __tablename__ = "timcash_company_account"

    id = Column(String(50), primary_key=True)
    
    # Soldes
    balance = Column(Float, default=0.0)  # Solde actuel
    total_commissions_received = Column(Float, default=0.0)  # Total des commissions reçues
    total_transferred_to_cinetpay = Column(Float, default=0.0)  # Total transféré à CinetPay
    
    # Statistiques
    total_recharges_count = Column(Integer, default=0)
    last_recharge_at = Column(DateTime, nullable=True)
    
    # Dates
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    def __repr__(self):
        return f"<TIMCashCompanyAccount: {self.balance} FCFA>"


class CinetPayTransfer(Base):
    """
    Transferts vers CinetPay
    Les 6% de commission TIM CASH sont reversés sur CinetPay
    """
    __tablename__ = "cinetpay_transfers"

    id = Column(String(50), primary_key=True)
    
    # Montant
    amount = Column(Float, nullable=False)
    
    # Référence
    reference = Column(String(100), unique=True, nullable=False)
    cinetpay_transaction_id = Column(String(100), nullable=True)
    
    # Statut
    status = Column(String(20), default="pending")  # pending, processing, completed, failed
    
    # Dates
    created_at = Column(DateTime, default=datetime.utcnow)
    completed_at = Column(DateTime, nullable=True)
    failed_at = Column(DateTime, nullable=True)
    
    # Informations supplémentaires
    failure_reason = Column(Text, nullable=True)
    notes = Column(Text, nullable=True)
    
    def __repr__(self):
        return f"<CinetPayTransfer {self.reference}: {self.amount} FCFA>"
