from datetime import datetime, timezone

from app.extensions import db


class PasswordFolder(db.Model):
    __tablename__ = 'password_folders'

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

    children = db.relationship('PasswordFolder',
                               backref=db.backref('parent', remote_side='PasswordFolder.id'),
                               lazy='dynamic')
    entries = db.relationship('PasswordEntry', backref='folder', lazy='dynamic',
                              cascade='all, delete-orphan')

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


class PasswordEntry(db.Model):
    __tablename__ = 'password_entries'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
    folder_id = db.Column(db.Integer, db.ForeignKey('password_folders.id'), nullable=True,
                          index=True)
    # All sensitive fields are encrypted client-side (AES-256-GCM)
    title_encrypted = db.Column(db.LargeBinary, nullable=False)
    url_encrypted = db.Column(db.LargeBinary, nullable=True)
    username_encrypted = db.Column(db.LargeBinary, nullable=True)
    password_encrypted = db.Column(db.LargeBinary, nullable=True)
    notes_encrypted = db.Column(db.LargeBinary, nullable=True)
    totp_secret_encrypted = db.Column(db.LargeBinary, nullable=True)
    passkey_data_encrypted = db.Column(db.LargeBinary, nullable=True)
    # IV for each entry (needed for AES-GCM decryption)
    iv = db.Column(db.LargeBinary, nullable=False)
    category = db.Column(db.String(100), nullable=True)  # Plaintext for filtering
    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))

    user = db.relationship('User', backref='password_entries')

    def to_dict(self):
        import base64
        return {
            'id': self.id,
            'folder_id': self.folder_id,
            'title_encrypted': base64.b64encode(self.title_encrypted).decode() if self.title_encrypted else None,
            'url_encrypted': base64.b64encode(self.url_encrypted).decode() if self.url_encrypted else None,
            'username_encrypted': base64.b64encode(self.username_encrypted).decode() if self.username_encrypted else None,
            'password_encrypted': base64.b64encode(self.password_encrypted).decode() if self.password_encrypted else None,
            'notes_encrypted': base64.b64encode(self.notes_encrypted).decode() if self.notes_encrypted else None,
            'totp_secret_encrypted': base64.b64encode(self.totp_secret_encrypted).decode() if self.totp_secret_encrypted else None,
            'passkey_data_encrypted': base64.b64encode(self.passkey_data_encrypted).decode() if self.passkey_data_encrypted else None,
            'iv': base64.b64encode(self.iv).decode() if self.iv else None,
            'category': self.category,
            '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 PasswordShare(db.Model):
    __tablename__ = 'password_shares'

    id = db.Column(db.Integer, primary_key=True)
    shareable_type = db.Column(db.String(20), nullable=False)  # 'entry' or 'folder'
    shareable_id = db.Column(db.Integer, nullable=False)
    shared_by_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    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')  # 'read', 'write', 'manage'
    # Re-encrypted data for the recipient (encrypted with recipient's public key)
    encrypted_key = db.Column(db.LargeBinary, nullable=True)
    created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))

    shared_by = db.relationship('User', foreign_keys=[shared_by_id], backref='password_shares_given')
    shared_with = db.relationship('User', foreign_keys=[shared_with_id], backref='password_shares_received')

    __table_args__ = (
        db.UniqueConstraint('shareable_type', 'shareable_id', 'shared_with_id',
                            name='uq_password_share'),
        db.Index('ix_password_shareable', 'shareable_type', 'shareable_id'),
    )
