//go:build integration

package mail_test

import (
	"testing"

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

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

	createBody := map[string]any{
		"name":      "Work",
		"email":     "work@example.com",
		"provider":  "custom",
		"imap_host": "imap.example.com",
		"imap_port": 993,
		"imap_tls":  true,
		"smtp_host": "smtp.example.com",
		"smtp_port": 587,
		"smtp_tls":  true,
		"username":  "work@example.com",
		"password":  "secret-pass",
	}

	resp, err := client.Post("/api/v1/mail/accounts", createBody)
	integrationtest.FailIf(err, t, "POST account")
	integrationtest.FailUnlessStatus(t, resp, 201)

	var created map[string]any
	integrationtest.DecodeJSON(t, resp, &created)
	accountID, _ := created["id"].(string)
	if accountID == "" {
		t.Fatalf("missing account id: %#v", created)
	}

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

	var list struct {
		Accounts []map[string]any `json:"accounts"`
	}
	integrationtest.DecodeJSON(t, resp, &list)
	if len(list.Accounts) != 1 {
		t.Fatalf("accounts len = %d, want 1", len(list.Accounts))
	}

	resp, err = client.Get("/api/v1/mail/accounts/" + accountID)
	integrationtest.FailIf(err, t, "GET account")
	integrationtest.FailUnlessStatus(t, resp, 200)

	resp, err = client.Put("/api/v1/mail/accounts/"+accountID, map[string]any{
		"name":      "Work Updated",
		"email":     "work@example.com",
		"imap_host": "imap.example.com",
		"imap_port": 993,
		"smtp_host": "smtp.example.com",
		"smtp_port": 587,
		"username":  "work@example.com",
	})
	integrationtest.FailIf(err, t, "PUT account")
	integrationtest.FailUnlessStatus(t, resp, 204)

	resp, err = client.Get("/api/v1/mail/accounts/" + accountID)
	integrationtest.FailIf(err, t, "GET account after update")
	integrationtest.FailUnlessStatus(t, resp, 200)
	var account map[string]any
	integrationtest.DecodeJSON(t, resp, &account)
	if account["name"] != "Work Updated" {
		t.Fatalf("name = %v", account["name"])
	}

	resp, err = client.Delete("/api/v1/mail/accounts/" + accountID)
	integrationtest.FailIf(err, t, "DELETE account")
	integrationtest.FailUnlessStatus(t, resp, 204)

	resp, err = client.Get("/api/v1/mail/accounts/" + accountID)
	integrationtest.FailIf(err, t, "GET deleted account")
	if resp.Status != 404 {
		t.Fatalf("status = %d, want 404", resp.Status)
	}
}
