import os
import requests
from apscheduler.schedulers.background import BackgroundScheduler
from django.utils.timezone import now
from .models import Message
from django.db import transaction

def send_scheduled_messages():
    mm_url = os.getenv("MM_URL")
    # debug
    # print(mm_url)
    headers = {"Content-Type": "application/json"}
    # 트랜잭션 시작
    with transaction.atomic():
        # 현재 시간 이전의 메시지 중 is_sent가 False인 메시지를 잠금
        messages = Message.objects.filter(
            send_time__lte=now(), is_sent=False
        ).select_for_update()

        for message in messages:
            try:
                # 메시지 전송
                data = {"text": f"{message.title}\n{message.text}"}
                response = requests.post(mm_url, json=data, headers=headers)

                # 성공적으로 전송되면 is_sent를 True로 업데이트
                if response.status_code == 200:
                    message.is_sent = True
                    message.save()
                    print(
                        f"Sent message: {message.title}, Response: {response.status_code}"
                    )
                else:
                    print(
                        f"Failed to send message: {message.title}, Response: {response.status_code}"
                    )

            except Exception as e:
                print(f"Error sending message: {message.title}, Error: {e}")


scheduler = BackgroundScheduler()
# scheduler.add_job(send_scheduled_messages, 'interval', minutes=1)  # 1분마다 실행
scheduler.add_job(send_scheduled_messages, "interval", seconds=30)  # 30초마다 실행

scheduler.start()
