//go:build integration

package mail_test

import (
	"testing"

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

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

	acctResp, err := client.Post("/api/v1/mail/accounts", map[string]any{
		"name":      "Drafts",
		"email":     "drafts@example.com",
		"imap_host": "imap.example.com",
		"imap_port": 993,
		"smtp_host": "smtp.example.com",
		"smtp_port": 587,
		"username":  "drafts@example.com",
		"password":  "secret",
	})
	integrationtest.FailIf(err, t, "create account")
	integrationtest.FailUnlessStatus(t, acctResp, 201)
	var acct map[string]string
	integrationtest.DecodeJSON(t, acctResp, &acct)

	createResp, err := client.Post("/api/v1/mail/drafts", map[string]any{
		"account_id": acct["id"],
		"subject":    "Draft subject",
		"body_text":  "Hello draft body",
		"to":         []string{"recipient@example.com"},
	})
	integrationtest.FailIf(err, t, "create draft")
	integrationtest.FailUnlessStatus(t, createResp, 201)
	var created map[string]string
	integrationtest.DecodeJSON(t, createResp, &created)
	draftID := created["id"]

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

	resp, err = client.Get("/api/v1/mail/drafts/" + draftID)
	integrationtest.FailIf(err, t, "get draft")
	integrationtest.FailUnlessStatus(t, resp, 200)

	resp, err = client.Put("/api/v1/mail/drafts/"+draftID, map[string]any{
		"account_id": acct["id"],
		"subject":    "Updated subject",
		"body_text":  "Updated body",
	})
	integrationtest.FailIf(err, t, "update draft")
	integrationtest.FailUnlessStatus(t, resp, 204)

	resp, err = client.Delete("/api/v1/mail/drafts/" + draftID)
	integrationtest.FailIf(err, t, "delete draft")
	integrationtest.FailUnlessStatus(t, resp, 204)
}
