"""
Modèle ENT - GMAO Collège
Intégration avec ENT77
"""
from datetime import datetime, timezone
from app_new.extensions import db


class EntCredential(db.Model):
    """Identifiants de connexion ENT77."""
    __tablename__ = "ent_credentials"
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
    ent_username_encrypted = db.Column(db.LargeBinary, nullable=False)
    ent_password_encrypted = db.Column(db.LargeBinary, nullable=False)
    last_check = db.Column(db.DateTime, nullable=True)
    last_msg_id = db.Column(db.String(100), nullable=True)
    is_active = db.Column(db.Boolean, default=True)
    created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
    
    # Relations
    user = db.relationship("User", backref="ent_credentials")
    
    def __repr__(self):
        return f"<EntCredential user={self.user_id}>"


class EntMessage(db.Model):
    """Message ENT stocké en base."""
    __tablename__ = "ent_messages"
    
    id = db.Column(db.String(100), primary_key=True)
    credential_id = db.Column(db.Integer, db.ForeignKey("ent_credentials.id"), nullable=False)
    subject = db.Column(db.String(500), nullable=False)
    sender_name = db.Column(db.String(200), nullable=True)
    sender_id = db.Column(db.String(100), nullable=True)
    date = db.Column(db.DateTime, nullable=True)
    body = db.Column(db.Text, nullable=True)
    is_forwarded = db.Column(db.Boolean, default=False)
    original_sender = db.Column(db.String(200), nullable=True)
    is_unread = db.Column(db.Boolean, default=False)
    has_attachment = db.Column(db.Boolean, default=False)
    attachment_count = db.Column(db.Integer, default=0)
    intervention_id = db.Column(db.Integer, db.ForeignKey("interventions.id"), nullable=True)
    created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
    
    def __repr__(self):
        return f"<EntMessage {self.subject}>"


class EntConfig(db.Model):
    """Configuration ENT77."""
    __tablename__ = "ent_config"
    __table_args__ = {'extend_existing': True}
    
    id = db.Column(db.Integer, primary_key=True)
    config_key = db.Column(db.String(100), nullable=False, unique=True)
    config_value = db.Column(db.Text, nullable=True)
    description = db.Column(db.Text, nullable=True)
    created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
    updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
    
    def __repr__(self):
        return f"<EntConfig {self.config_key}>"


# Note: Le service ENT (ent_service.py) et le crypto (ent_crypto.py) restent des services externes
# Les templates sont dans app_new/ent/templates/