//go:build integration

package mail_test

import (
	"testing"

	"github.com/ultisuite/ulti-backend/internal/integrationtest"
)

func TestRulesAndWebhooks(t *testing.T) {
	h := integrationtest.RequireHarness(t)
	client, _ := integrationtest.RequireUserClient(t, h)

	ruleResp, err := client.Post("/api/v1/mail/rules", map[string]any{
		"name": "Archive invoices",
		"conditions": []map[string]string{
			{"field": "subject", "operator": "contains", "value": "invoice"},
		},
		"actions": []map[string]string{
			{"type": "label", "value": "finance"},
		},
	})
	integrationtest.FailIf(err, t, "create rule")
	integrationtest.FailUnlessStatus(t, ruleResp, 201)
	var rule map[string]string
	integrationtest.DecodeJSON(t, ruleResp, &rule)
	ruleID := rule["id"]

	resp, err := client.Get("/api/v1/mail/rules")
	integrationtest.FailIf(err, t, "list rules")
	integrationtest.FailUnlessStatus(t, resp, 200)

	simResp, err := client.Post("/api/v1/mail/rules/simulate", map[string]any{
		"message": map[string]any{
			"subject": "Invoice Q1",
			"from":    "billing@example.com",
		},
		"rule": map[string]any{
			"conditions": []map[string]string{
				{"field": "subject", "operator": "contains", "value": "invoice"},
			},
			"actions": []map[string]string{
				{"type": "label", "value": "finance"},
			},
		},
	})
	integrationtest.FailIf(err, t, "simulate rule")
	integrationtest.FailUnlessStatus(t, simResp, 200)

	webhookResp, err := client.Post("/api/v1/mail/webhooks", map[string]any{
		"name":          "Slack hook",
		"url":           "https://hooks.example.com/slack",
		"method":        "POST",
		"body_template": `{"text":"$subject"}`,
		"event_types":   []string{"mail.received"},
		"mail_scope": map[string]any{
			"all_accounts": true,
		},
	})
	integrationtest.FailIf(err, t, "create webhook")
	integrationtest.FailUnlessStatus(t, webhookResp, 201)
	var hook map[string]string
	integrationtest.DecodeJSON(t, webhookResp, &hook)

	resp, err = client.Get("/api/v1/mail/webhooks")
	integrationtest.FailIf(err, t, "list webhooks")
	integrationtest.FailUnlessStatus(t, resp, 200)

	delResp, err := client.Delete("/api/v1/mail/webhooks/" + hook["id"])
	integrationtest.FailIf(err, t, "delete webhook")
	integrationtest.FailUnlessStatus(t, delResp, 204)

	delRule, err := client.Delete("/api/v1/mail/rules/" + ruleID)
	integrationtest.FailIf(err, t, "delete rule")
	integrationtest.FailUnlessStatus(t, delRule, 204)
}
