from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .models import AIChatHistory, Profile
from django.db.models import Q

def index(request):
    if request.user.is_authenticated:
        return redirect('dashboard')
    return render(request, 'core/index.html')

@login_required
def dashboard(request):
    query = request.GET.get('q', '')
    profile = Profile.objects.get(user=request.user)
    chats = AIChatHistory.objects.filter(company=profile.company)

    if query:
        chats = chats.filter(
            Q(chat_title__icontains=query) | Q(chat_content__icontains=query)
        ).order_by('-chat_last_date')
    else:
        chats = chats.order_by('-chat_last_date')[:10]

    context = {
        'chats': chats,
        'query': query,
        'company': profile.company
    }
    return render(request, 'core/dashboard.html', context)

def chat_detail(request, pk):
    profile = Profile.objects.get(user=request.user)
    chat = AIChatHistory.objects.get(pk=pk, company=profile.company)
    return render(request, 'core/chat_detail.html', {'chat': chat})