from datetime import datetime, timezone

from app.extensions import db


class EmailAccount(db.Model):
    __tablename__ = 'email_accounts'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
    display_name = db.Column(db.String(100), nullable=False)  # e.g. "Arbeit", "Privat"
    email_address = db.Column(db.String(255), nullable=False)
    imap_host = db.Column(db.String(255), nullable=False)
    imap_port = db.Column(db.Integer, default=993)
    imap_ssl = db.Column(db.Boolean, default=True)
    smtp_host = db.Column(db.String(255), nullable=False)
    smtp_port = db.Column(db.Integer, default=587)
    smtp_ssl = db.Column(db.Boolean, default=True)  # STARTTLS
    username = db.Column(db.String(255), nullable=False)
    password_encrypted = db.Column(db.LargeBinary, nullable=False)
    is_default = db.Column(db.Boolean, default=False)
    sort_order = db.Column(db.Integer, default=0)
    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 to_dict(self):
        return {
            'id': self.id,
            'display_name': self.display_name,
            'email_address': self.email_address,
            'imap_host': self.imap_host,
            'imap_port': self.imap_port,
            'imap_ssl': self.imap_ssl,
            'smtp_host': self.smtp_host,
            'smtp_port': self.smtp_port,
            'smtp_ssl': self.smtp_ssl,
            'username': self.username,
            'is_default': self.is_default,
            'sort_order': self.sort_order,
        }
