"""File upload model for RateRight - supports multiple storage backends"""
from datetime import datetime
from sqlalchemy import Enum as SQLEnum
from enum import Enum

from ..extensions import db
from .base import BaseModel


class StorageBackend(Enum):
    """Storage backend types"""
    LOCAL = "local"
    CLOUDINARY = "cloudinary"


class FileCategory(Enum):
    """File categories for organization"""
    PROFILE_PICTURE = "profile_picture"
    MESSAGE_ATTACHMENT = "message_attachment"
    CONTRACT_DOCUMENT = "contract_document"
    JOB_PHOTO = "job_photo"
    CERTIFICATION = "certification"
    INVOICE = "invoice"
    INSURANCE_DOCUMENT = "insurance_document"
    OTHER = "other"


class FileUpload(BaseModel):
    """Universal file upload model - works with any storage backend"""
    
    __tablename__ = "file_uploads"
    
    # Ownership
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    
    # File metadata
    filename = db.Column(db.String(500), nullable=False)
    original_filename = db.Column(db.String(500), nullable=False)
    file_type = db.Column(db.String(100))  # MIME type: image/jpeg, application/pdf, etc.
    file_size = db.Column(db.BigInteger)  # Size in bytes
    
    # Storage information
    storage_backend = db.Column(SQLEnum(StorageBackend), default=StorageBackend.LOCAL, nullable=False)
    storage_path = db.Column(db.Text)  # Local path or cloud identifier
    public_url = db.Column(db.Text)  # Full URL to access the file
    
    # Organization
    category = db.Column(SQLEnum(FileCategory), default=FileCategory.OTHER)
    
    # Optional context linking (what is this file related to?)
    message_id = db.Column(db.Integer, db.ForeignKey('messages.id'), nullable=True)
    job_id = db.Column(db.Integer, db.ForeignKey('jobs.id'), nullable=True)
    contract_id = db.Column(db.Integer, db.ForeignKey('contracts.id'), nullable=True)
    
    # Image-specific metadata (if applicable)
    width = db.Column(db.Integer)
    height = db.Column(db.Integer)
    
    # Cloud provider specific fields (JSON for flexibility)
    cloud_metadata = db.Column(db.JSON)  # Store provider-specific data
    
    # Soft delete support
    is_deleted = db.Column(db.Boolean, default=False)
    deleted_at = db.Column(db.DateTime)
    
    # Relationships
    user = db.relationship('User', backref=db.backref('uploaded_files', lazy='dynamic'))
    message = db.relationship('Message', backref=db.backref('attachments', lazy='dynamic'))
    job = db.relationship('Job', backref=db.backref('photos', lazy='dynamic'))
    contract = db.relationship('Contract', backref=db.backref('documents', lazy='dynamic'))
    
    # Indexes for performance
    __table_args__ = (
        db.Index('idx_file_user_category', 'user_id', 'category'),
        db.Index('idx_file_message', 'message_id'),
        db.Index('idx_file_job', 'job_id'),
        db.Index('idx_file_contract', 'contract_id'),
        db.Index('idx_file_storage', 'storage_backend'),
    )
    
    @property
    def file_size_mb(self):
        """Get file size in MB"""
        if self.file_size:
            return round(self.file_size / (1024 * 1024), 2)
        return 0
    
    @property
    def is_image(self):
        """Check if file is an image"""
        if self.file_type:
            return self.file_type.startswith('image/')
        return False
    
    @property
    def extension(self):
        """Get file extension"""
        if self.filename:
            return self.filename.rsplit('.', 1)[1].lower() if '.' in self.filename else ''
        return ''
    
    def soft_delete(self):
        """Soft delete the file"""
        self.is_deleted = True
        self.deleted_at = datetime.utcnow()
        db.session.commit()
    
    def __repr__(self):
        return f'<FileUpload {self.filename} by User {self.user_id}>'
