from django.core.management.base import BaseCommand
from django.core.mail import EmailMessage
from django.template.loader import render_to_string
from core import utils

from core.models import CustomUser

class Command(BaseCommand):
    def handle(self, *args, **kwargs):
        print("Send welcome email to coop managers\n")
        
        managers = CustomUser.objects.filter(role='COOP_MANAGER')

        for manager in managers:
            try:
                password = utils.generate_password(12)
                manager.set_password(password)
                manager.save()
            except:
                return Response({'error': f"Could not set new password [{str(type(e))}]: {str(e)}"}, status=500)
            link = "https://latienda.coop/login"
            company_message = render_to_string('welcome_coop.html', {
                'manager': manager,
                'password': password,
                'link': link
            })
            # send email to company
            subject = "Bienvenid@ a LaTienda.COOP"
            email = EmailMessage(subject, company_message, to=[manager.email])
            email.content_subtype = "html"
            email.send()

        print(f"Messages sent to {len(managers)} coop managers")