package service

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"system-altrak/pkg/utils"
	"time"

	"go.uber.org/zap"
)

type NotificationService interface {
	SendApprovalNotification(documentType string, identifier string, approvedBy string)
}

type notificationServiceImpl struct {
	telegramToken  string
	telegramChatID string
	client         *http.Client
}

func NewNotificationService(telegramToken string, telegramChatID string) NotificationService {
	return &notificationServiceImpl{
		telegramToken:  telegramToken,
		telegramChatID: telegramChatID,
		client:         &http.Client{Timeout: 10 * time.Second},
	}
}

func (s *notificationServiceImpl) SendApprovalNotification(documentType string, identifier string, approvedBy string) {
	if s.telegramToken == "" || s.telegramChatID == "" {
		utils.Log.Warn("Telegram token atau Chat ID tidak dikonfigurasi, mengabaikan notifikasi pengesahan.")
		return
	}

	go func() {
		// Asynchronous notification sending
		msg := fmt.Sprintf("✅ *Pemberitahuan Sistem Altrak*\n\nDokumen *%s* (%s) telah berhasil diverifikasi/disahkan oleh user ID %s pada %s.",
			documentType, identifier, approvedBy, time.Now().Format("02-01-2006 15:04:05"))

		payload := map[string]interface{}{
			"chat_id":    s.telegramChatID,
			"text":       msg,
			"parse_mode": "Markdown",
		}

		jsonData, err := json.Marshal(payload)
		if err != nil {
			utils.Log.Error("Gagal menyusun payload notifikasi Telegram", zap.Error(err))
			return
		}
		url := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", s.telegramToken)

		resp, err := s.client.Post(url, "application/json", bytes.NewBuffer(jsonData))
		if err != nil {
			utils.Log.Error("Gagal mengirim notifikasi Telegram", zap.Error(err))
			return
		}
		defer resp.Body.Close()

		if resp.StatusCode != http.StatusOK {
			utils.Log.Error("Notifikasi Telegram gagal diterima oleh server Telegram", zap.Int("status", resp.StatusCode))
		} else {
			utils.Log.Info("✅ Notifikasi Telegram terkirim", zap.String("document", identifier))
		}
	}()
}
