from django.contrib import admin
from .models import Company, Profile, AIChatHistory, AIConfiguration, SyncHistoryLog
from .utils import encrypt_value, decrypt_value

@admin.register(Company)
class CompanyAdmin(admin.ModelAdmin):
    list_display = ('name', 'tenant_id', 'created_at')
    search_fields = ('name', 'tenant_id')

@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
    list_display = ('user', 'company', 'role')
    list_filter = ('company', 'role')

@admin.register(AIConfiguration)
class AIConfigurationAdmin(admin.ModelAdmin):
    list_display = ('company', 'provider', 'is_active', 'last_sync')
    list_filter = ('provider', 'is_active')
    
    def save_model(self, request, obj, form, change):
        # Encrypt API key before saving if it's changed or new
        if 'api_key' in form.changed_data or not change:
            obj.api_key = encrypt_value(obj.api_key)
        super().save_model(request, obj, form, change)

@admin.register(AIChatHistory)
class AIChatHistoryAdmin(admin.ModelAdmin):
    list_display = ('chat_title', 'company', 'ai_chat_engine', 'chat_last_date')
    list_filter = ('company', 'ai_chat_engine')
    search_fields = ('chat_title', 'chat_content')

@admin.register(SyncHistoryLog)
class SyncHistoryLogAdmin(admin.ModelAdmin):
    list_display = ('timestamp', 'company', 'configuration', 'status', 'records_synced')
    list_filter = ('status', 'company')
    readonly_fields = ('timestamp', 'company', 'configuration', 'status', 'records_synced', 'error_message')
