package apitokens

import "testing"

func TestRequirementForMailMessages(t *testing.T) {
	req, ok := RequirementForRequest("GET", "/api/v1/mail/messages", "")
	if !ok || req.Resource != "mail.messages" || req.Write {
		t.Fatalf("got %+v ok=%v", req, ok)
	}
}

func TestRequirementForMailSend(t *testing.T) {
	req, ok := RequirementForRequest("POST", "/api/v1/mail/send", "")
	if !ok || req.Resource != "mail.send" || !req.Write {
		t.Fatalf("got %+v ok=%v", req, ok)
	}
}

func TestRequirementForDriveUpload(t *testing.T) {
	req, ok := RequirementForRequest("POST", "/api/v1/drive/files/Projects", "")
	if !ok || req.Resource != "drive.upload" || !req.Write || req.ScopeHint != ScopeDrivePathFromURL {
		t.Fatalf("got %+v ok=%v", req, ok)
	}
}

func TestRequirementForAutomationWebhooks(t *testing.T) {
	req, ok := RequirementForRequest("DELETE", "/api/v1/mail/webhooks/abc", "")
	if !ok || req.Resource != "automation.webhooks" || !req.Write {
		t.Fatalf("got %+v ok=%v", req, ok)
	}
}

func TestSearchRequirementsMultipleTypes(t *testing.T) {
	reqs := SearchRequirements("mail,contacts,drive")
	if len(reqs) != 3 {
		t.Fatalf("len = %d", len(reqs))
	}
}

func TestAllowsRequirementAlternatives(t *testing.T) {
	auth := &AuthContext{
		Permissions: []PermissionGrant{
			{Resource: "drive.files", Read: true},
		},
	}
	req := Requirement{Resource: "drive.folders", Alternatives: []string{"drive.files"}, Write: false}
	if !AllowsRequirement(auth, req) {
		t.Fatal("expected drive.files alternative to satisfy folders read")
	}
}

func TestExtractMailAccountIDFromPath(t *testing.T) {
	got := ExtractMailAccountID("/api/v1/mail/accounts/550e8400-e29b-41d4-a716-446655440000/sync", "")
	if got != "550e8400-e29b-41d4-a716-446655440000" {
		t.Fatalf("got %q", got)
	}
}

func TestExtractDrivePathFromURL(t *testing.T) {
	got := ExtractDrivePathFromURL("/api/v1/drive/files/Projects/docs")
	want := "/Projects/docs"
	if got != want {
		t.Fatalf("got %q want %q", got, want)
	}
}
