from datetime import datetime, timezone

from app.extensions import db


class AddressBook(db.Model):
    __tablename__ = 'address_books'

    id = db.Column(db.Integer, primary_key=True)
    owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
    name = db.Column(db.String(255), nullable=False)
    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))

    contacts = db.relationship('Contact', backref='address_book', lazy='dynamic',
                               cascade='all, delete-orphan')
    shares = db.relationship('AddressBookShare', backref='address_book', lazy='dynamic',
                             cascade='all, delete-orphan')

    def to_dict(self):
        return {
            'id': self.id,
            'owner_id': self.owner_id,
            'name': self.name,
            'description': self.description,
            'created_at': self.created_at.isoformat() if self.created_at else None,
        }


class Contact(db.Model):
    __tablename__ = 'contacts'

    id = db.Column(db.Integer, primary_key=True)
    address_book_id = db.Column(db.Integer, db.ForeignKey('address_books.id'),
                                nullable=False, index=True)
    uid = db.Column(db.String(255), unique=True, nullable=False)
    vcard_data = db.Column(db.Text, nullable=False)  # Full VCARD
    display_name = db.Column(db.String(255), nullable=True, index=True)
    email = db.Column(db.String(255), nullable=True)
    phone = db.Column(db.String(50), 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 to_dict(self):
        return {
            'id': self.id,
            'address_book_id': self.address_book_id,
            'uid': self.uid,
            'display_name': self.display_name,
            'email': self.email,
            'phone': self.phone,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
        }


class AddressBookShare(db.Model):
    __tablename__ = 'address_book_shares'

    id = db.Column(db.Integer, primary_key=True)
    address_book_id = db.Column(db.Integer, db.ForeignKey('address_books.id'),
                                nullable=False, index=True)
    shared_with_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
    permission = db.Column(db.String(20), nullable=False, default='read')

    shared_with = db.relationship('User', backref='shared_address_books')

    __table_args__ = (
        db.UniqueConstraint('address_book_id', 'shared_with_id', name='uq_addressbook_share'),
    )
