from app.extensions import db
from datetime import datetime

class SocialNetwork(db.Model):
    """Modelo para configurar las redes sociales disponibles para compartir contenido."""
    __tablename__ = 'social_networks'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)  # Nombre: Facebook, Twitter, etc.
    icon = db.Column(db.String(50))  # Clase de icono Font Awesome: fab fa-facebook
    color = db.Column(db.String(20))  # Color del botón: #3b5998 para Facebook
    url_pattern = db.Column(db.String(255), nullable=False)  # https://www.facebook.com/sharer/sharer.php?u={url}&quote={title}
    is_active = db.Column(db.Boolean, default=True)
    position = db.Column(db.Integer, default=0)  # Para ordenar
    requires_mobile = db.Column(db.Boolean, default=False)  # Para WhatsApp en móvil
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    def __repr__(self):
        return f'<SocialNetwork {self.name}>'
    
    def get_share_url(self, url, title, summary=None):
        """Genera la URL de compartir basada en el patrón definido."""
        share_url = self.url_pattern
        share_url = share_url.replace('{url}', url)
        share_url = share_url.replace('{title}', title)
        if summary and '{summary}' in share_url:
            share_url = share_url.replace('{summary}', summary)
        return share_url

# Migración inicial para crear las redes sociales predeterminadas
def create_default_social_networks():
    """Crea las redes sociales predeterminadas si no existen."""
    default_networks = [
        {
            'name': 'Facebook',
            'icon': 'fab fa-facebook-f',
            'color': '#3b5998',
            'url_pattern': 'https://www.facebook.com/sharer/sharer.php?u={url}&quote={title}',
            'position': 1,
            'requires_mobile': False
        },
        {
            'name': 'X',
            'icon': 'fa-brands fa-x-twitter',
            'color': '#000000',
            'url_pattern': 'https://twitter.com/intent/tweet?text={title}&url={url}',
            'position': 2,
            'requires_mobile': False
        },
        {
            'name': 'LinkedIn',
            'icon': 'fab fa-linkedin-in',
            'color': '#0077b5',
            'url_pattern': 'https://www.linkedin.com/sharing/share-offsite/?url={url}',
            'position': 3,
            'requires_mobile': False
        },
        {
            'name': 'WhatsApp',
            'icon': 'fab fa-whatsapp',
            'color': '#25d366',
            'url_pattern': 'https://wa.me/?text={title}%20{url}',
            'position': 4,
            'requires_mobile': True
        },
        {
            'name': 'Telegram',
            'icon': 'fab fa-telegram-plane',
            'color': '#0088cc',
            'url_pattern': 'https://t.me/share/url?url={url}&text={title}',
            'position': 5,
            'requires_mobile': False
        },
        {
            'name': 'Email',
            'icon': 'fas fa-envelope',
            'color': '#666666',
            'url_pattern': 'mailto:?subject={title}&body={url}',
            'position': 6,
            'requires_mobile': False
        }
    ]
    
    # Insertar solo si no existen
    for network_data in default_networks:
        existing = SocialNetwork.query.filter_by(name=network_data['name']).first()
        if not existing:
            network = SocialNetwork(**network_data)
            db.session.add(network)
    
    db.session.commit()
