//go:build integration

package mail_test

import (
	"testing"

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

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

	createResp, err := client.Post("/api/v1/mail/api-tokens", map[string]any{
		"name": "integration agent",
		"permissions": []map[string]any{
			{"resource": "mail.messages", "read": true, "write": false},
			{"resource": "mail.settings", "read": true, "write": false},
		},
		"mail_scope": map[string]any{
			"all_accounts": true,
			"account_ids":  []string{},
		},
		"drive_scope": map[string]any{
			"all_folders":  true,
			"folder_paths": []string{},
		},
	})
	integrationtest.FailIf(err, t, "create token")
	integrationtest.FailUnlessStatus(t, createResp, 201)

	var created map[string]any
	integrationtest.DecodeJSON(t, createResp, &created)
	token, _ := created["token"].(string)
	tokenID, _ := created["id"].(string)
	if token == "" || tokenID == "" {
		t.Fatalf("missing token fields: %#v", created)
	}

	apiClient := client.WithToken(token)
	resp, err := apiClient.Get("/api/v1/mail/settings")
	integrationtest.FailIf(err, t, "use api token")
	integrationtest.FailUnlessStatus(t, resp, 200)

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

	delResp, err := client.Delete("/api/v1/mail/api-tokens/" + tokenID)
	integrationtest.FailIf(err, t, "revoke token")
	integrationtest.FailUnlessStatus(t, delResp, 204)

	resp, err = apiClient.Get("/api/v1/mail/settings")
	integrationtest.FailIf(err, t, "use revoked token")
	if resp.Status != 401 {
		t.Fatalf("status = %d, want 401 after revoke", resp.Status)
	}
}
