from django.contrib import admin
from django.contrib.admin import action
from api_v1.models import UploadedFile, DataSync
from .tasks import backup_database


@admin.register(UploadedFile)
class UploadedFileAdmin(admin.ModelAdmin):
    list_display = ['id', 'original_filename', 'owner', 'file_size', 'content_type', 'created_at', 'is_deleted']
    list_filter = ['is_deleted', 'created_at', 'content_type']
    search_fields = ['original_filename', 'owner__username']
    readonly_fields = ['created_at', 'file_size', 'content_type']
    date_hierarchy = 'created_at'
    ordering = ['-created_at']
    actions = ['backup_database']
    
    def get_queryset(self, request):
        # 在管理界面显示所有文件，包括已删除的
        return super().get_queryset(request).select_related('owner')

    @action(description='备份数据库')
    def backup_database(self, request, queryset):
        backup_database.delay()


@admin.register(DataSync)
class DataSyncAdmin(admin.ModelAdmin):
    list_display = ['id', 'table_name', 'page_index', 'page_size', 'total_count', 'synced_rows', 'last_ctime', 'last_rowid', 'note']
    list_filter = ['table_name', 'created_at']
    search_fields = ['table_name', 'last_rowid', 'note']
    readonly_fields = ['created_at', 'updated_at']
    date_hierarchy = 'created_at'
    ordering = ['-created_at']
