//go:build integration

package mail_test

import (
	"testing"

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

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

	// Create mail account first (folders are account-scoped).
	acctResp, err := client.Post("/api/v1/mail/accounts", map[string]any{
		"name":      "Labels",
		"email":     "labels@example.com",
		"imap_host": "imap.example.com",
		"imap_port": 993,
		"smtp_host": "smtp.example.com",
		"smtp_port": 587,
		"username":  "labels@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)
	accountID := acct["id"]

	labelResp, err := client.Post("/api/v1/mail/labels", map[string]string{
		"name":  "Important",
		"color": "#ff0000",
	})
	integrationtest.FailIf(err, t, "create label")
	integrationtest.FailUnlessStatus(t, labelResp, 201)
	var label map[string]string
	integrationtest.DecodeJSON(t, labelResp, &label)
	labelID := label["id"]
	if labelID == "" {
		t.Fatal("missing label id")
	}

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

	folderResp, err := client.Post("/api/v1/mail/folders", map[string]any{
		"account_id":  accountID,
		"name":        "Projects",
		"folder_type": "custom",
	})
	integrationtest.FailIf(err, t, "create folder")
	integrationtest.FailUnlessStatus(t, folderResp, 201)
	var folder map[string]string
	integrationtest.DecodeJSON(t, folderResp, &folder)
	_ = folder["id"]

	resp, err = client.Get("/api/v1/mail/folders?account_id=" + accountID)
	integrationtest.FailIf(err, t, "list folders")
	integrationtest.FailUnlessStatus(t, resp, 200)

	ufResp, err := client.Post("/api/v1/mail/unified-folders", map[string]any{
		"name":       "All Projects",
		"account_id": accountID,
	})
	integrationtest.FailIf(err, t, "create unified folder")
	integrationtest.FailUnlessStatus(t, ufResp, 201)

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

	resp, err = client.Delete("/api/v1/mail/labels/" + labelID)
	integrationtest.FailIf(err, t, "delete label")
	integrationtest.FailUnlessStatus(t, resp, 204)
}
