from rest_framework import viewsets, permissions
# ŠEIT BIJA KĻŪDA: Modelis saucas 'Projekts', nevis 'Project'
from .models import Projekts, Uzdevums, AgentaZina
from .serializers import ProjectSerializer, TaskSerializer, AgentaZinaSerializer

class ProjectViewSet(viewsets.ModelViewSet):
    serializer_class = ProjectSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        user = self.request.user
        
        # 1. Ja lietotājs ir ADMINS vai PERSONĀLS -> Redz visu
        if user.is_staff or getattr(user, 'role', '') == 'admin':
            return Projekts.objects.all()
        
        # 2. Ja parasts KLIENTS -> Redz tikai tos projektus, kur viņš ir 'klients'
        # Mēs izmantojam Tavu modeli: klients = models.ForeignKey(...)
        return Projekts.objects.filter(klients=user)

class TaskViewSet(viewsets.ModelViewSet):
    serializer_class = TaskSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        user = self.request.user
        if user.is_staff or getattr(user, 'role', '') == 'admin':
            return Uzdevums.objects.all().order_by('-izveidots')
        return Uzdevums.objects.filter(klients=user).order_by('-izveidots')
        
    def perform_create(self, serializer):
        # Klients, kas izveido uzdevumu, automātiski kļūst par īpašnieku (ja nav admins un nenorāda citu)
        serializer.save(klients=self.request.user)

    def perform_update(self, serializer):
        old_status = serializer.instance.statuss
        new_status = serializer.validated_data.get('statuss', old_status)
        instance = serializer.save()
        
        if old_status != new_status and instance.klients.telegram_id:
            try:
                from telegram_bot.handlers import send_message
                status_map = {'IDEJA': '💡 Ideja', 'GAIDA': '📝 Gaida', 'PROCESA': '⚙️ Procesā', 'PABEIGTS': '✅ Pabeigts'}
                txt_status = status_map.get(new_status, new_status)
                texto = f"🔔 *Statusa Atjauninājums*\n\nTavs uzdevums *{instance.tituls}* ir pārcelts uz: {txt_status}!"
                
                reply_markup = None
                if new_status in ['PROCESA', 'GAIDA', 'IDEJA']:
                    reply_markup = {
                        "inline_keyboard": [[
                            {"text": "✅ Apstiprināt Pabeigšanai", "callback_data": f"task_approve_{instance.id}"}
                        ]]
                    }
                
                send_message(instance.klients.telegram_id, texto, reply_markup=reply_markup)
            except Exception as e:
                import logging
                logging.getLogger(__name__).error(f"Telegram notification error: {e}")

class AgentaZinaViewSet(viewsets.ReadOnlyModelViewSet):
    serializer_class = AgentaZinaSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        user = self.request.user
        if user.is_staff or getattr(user, 'role', '') == 'admin':
            return AgentaZina.objects.all().order_by('-izveidots')[:10]
        return AgentaZina.objects.filter(klients=user).order_by('-izveidots')[:10]