import uuid
from django import forms
from apps.customers.models import Customer
from .models import NotificationTemplate
from .queries import companies


class TemplateForm(forms.ModelForm):
    class Meta:
        model = NotificationTemplate
        fields = ["company", "code", "name", "channel", "subject", "body", "is_active"]

    def __init__(self, *args, actor, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["company"].queryset = companies(actor, "communications.manage_templates")
        if not self.instance._state.adding:
            for name in ("company", "code", "channel"):
                self.fields[name].disabled = True


class ManualForm(forms.Form):
    template = forms.ModelChoiceField(queryset=NotificationTemplate.objects.none())
    customer = forms.ModelChoiceField(queryset=Customer.objects.none())
    request_key = forms.UUIDField(widget=forms.HiddenInput, initial=uuid.uuid4)

    def __init__(self, *args, actor, **kwargs):
        super().__init__(*args, **kwargs)
        allowed = companies(actor, "communications.send_notification")
        self.fields["template"].queryset = NotificationTemplate.objects.filter(company__in=allowed, is_active=True)
        self.fields["customer"].queryset = Customer.objects.filter(company__in=allowed, is_active=True)

    def clean(self):
        data = super().clean()
        if data.get("template") and data.get("customer") and data["template"].company_id != data["customer"].company_id:
            raise forms.ValidationError("Customer and template must belong to the same company.")
        return data
