// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.

package openai

import (
	"context"
	"errors"
	"net/http"
	"net/url"
	"slices"

	"github.com/openai/openai-go/v3/internal/apijson"
	"github.com/openai/openai-go/v3/internal/apiquery"
	"github.com/openai/openai-go/v3/internal/requestconfig"
	"github.com/openai/openai-go/v3/option"
	"github.com/openai/openai-go/v3/packages/pagination"
	"github.com/openai/openai-go/v3/packages/param"
	"github.com/openai/openai-go/v3/packages/respjson"
	"github.com/openai/openai-go/v3/shared/constant"
)

// AdminOrganizationProjectUserRoleService contains methods and other services that
// help with interacting with the openai API.
//
// Note, unlike clients, this service does not read variables from the environment
// automatically. You should not instantiate this service directly, and instead use
// the [NewAdminOrganizationProjectUserRoleService] method instead.
type AdminOrganizationProjectUserRoleService struct {
	Options []option.RequestOption
}

// NewAdminOrganizationProjectUserRoleService generates a new service that applies
// the given options to each request. These options are applied after the parent
// client's options (if there is one), and before any request-specific options.
func NewAdminOrganizationProjectUserRoleService(opts ...option.RequestOption) (r AdminOrganizationProjectUserRoleService) {
	r = AdminOrganizationProjectUserRoleService{}
	r.Options = opts
	return
}

// Assigns a project role to a user within a project.
func (r *AdminOrganizationProjectUserRoleService) New(ctx context.Context, projectID string, userID string, body AdminOrganizationProjectUserRoleNewParams, opts ...option.RequestOption) (res *AdminOrganizationProjectUserRoleNewResponse, err error) {
	var preClientOpts = []option.RequestOption{requestconfig.WithAdminAPIKeyAuthSecurity()}
	opts = slices.Concat(preClientOpts, r.Options, opts)
	if projectID == "" {
		err = errors.New("missing required project_id parameter")
		return nil, err
	}
	if userID == "" {
		err = errors.New("missing required user_id parameter")
		return nil, err
	}
	path := requestconfig.FormatPath("projects/%s/users/%s/roles", projectID, userID)
	err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
	return res, err
}

// Retrieves a project role assigned to a user.
func (r *AdminOrganizationProjectUserRoleService) Get(ctx context.Context, projectID string, userID string, roleID string, opts ...option.RequestOption) (res *AdminOrganizationProjectUserRoleGetResponse, err error) {
	var preClientOpts = []option.RequestOption{requestconfig.WithAdminAPIKeyAuthSecurity()}
	opts = slices.Concat(preClientOpts, r.Options, opts)
	if projectID == "" {
		err = errors.New("missing required project_id parameter")
		return nil, err
	}
	if userID == "" {
		err = errors.New("missing required user_id parameter")
		return nil, err
	}
	if roleID == "" {
		err = errors.New("missing required role_id parameter")
		return nil, err
	}
	path := requestconfig.FormatPath("projects/%s/users/%s/roles/%s", projectID, userID, roleID)
	err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
	return res, err
}

// Lists the project roles assigned to a user within a project.
func (r *AdminOrganizationProjectUserRoleService) List(ctx context.Context, projectID string, userID string, query AdminOrganizationProjectUserRoleListParams, opts ...option.RequestOption) (res *pagination.NextCursorPage[AdminOrganizationProjectUserRoleListResponse], err error) {
	var raw *http.Response
	var preClientOpts = []option.RequestOption{requestconfig.WithAdminAPIKeyAuthSecurity()}
	opts = slices.Concat(preClientOpts, r.Options, opts)
	opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...)
	if projectID == "" {
		err = errors.New("missing required project_id parameter")
		return nil, err
	}
	if userID == "" {
		err = errors.New("missing required user_id parameter")
		return nil, err
	}
	path := requestconfig.FormatPath("projects/%s/users/%s/roles", projectID, userID)
	cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...)
	if err != nil {
		return nil, err
	}
	err = cfg.Execute()
	if err != nil {
		return nil, err
	}
	res.SetPageConfig(cfg, raw)
	return res, nil
}

// Lists the project roles assigned to a user within a project.
func (r *AdminOrganizationProjectUserRoleService) ListAutoPaging(ctx context.Context, projectID string, userID string, query AdminOrganizationProjectUserRoleListParams, opts ...option.RequestOption) *pagination.NextCursorPageAutoPager[AdminOrganizationProjectUserRoleListResponse] {
	return pagination.NewNextCursorPageAutoPager(r.List(ctx, projectID, userID, query, opts...))
}

// Unassigns a project role from a user within a project.
func (r *AdminOrganizationProjectUserRoleService) Delete(ctx context.Context, projectID string, userID string, roleID string, opts ...option.RequestOption) (res *AdminOrganizationProjectUserRoleDeleteResponse, err error) {
	var preClientOpts = []option.RequestOption{requestconfig.WithAdminAPIKeyAuthSecurity()}
	opts = slices.Concat(preClientOpts, r.Options, opts)
	if projectID == "" {
		err = errors.New("missing required project_id parameter")
		return nil, err
	}
	if userID == "" {
		err = errors.New("missing required user_id parameter")
		return nil, err
	}
	if roleID == "" {
		err = errors.New("missing required role_id parameter")
		return nil, err
	}
	path := requestconfig.FormatPath("projects/%s/users/%s/roles/%s", projectID, userID, roleID)
	err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...)
	return res, err
}

// Role assignment linking a user to a role.
type AdminOrganizationProjectUserRoleNewResponse struct {
	// Always `user.role`.
	Object constant.UserRole `json:"object" default:"user.role"`
	// Details about a role that can be assigned through the public Roles API.
	Role Role `json:"role" api:"required"`
	// Represents an individual `user` within an organization.
	User OrganizationUser `json:"user" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Object      respjson.Field
		Role        respjson.Field
		User        respjson.Field
		ExtraFields map[string]respjson.Field
		raw         string
	} `json:"-"`
}

// Returns the unmodified JSON received from the API
func (r AdminOrganizationProjectUserRoleNewResponse) RawJSON() string { return r.JSON.raw }
func (r *AdminOrganizationProjectUserRoleNewResponse) UnmarshalJSON(data []byte) error {
	return apijson.UnmarshalRoot(data, r)
}

// Detailed information about a role assignment entry returned when listing
// assignments.
type AdminOrganizationProjectUserRoleGetResponse struct {
	// Identifier for the role.
	ID string `json:"id" api:"required"`
	// Principals from which the role assignment is inherited, when available.
	AssignmentSources []AdminOrganizationProjectUserRoleGetResponseAssignmentSource `json:"assignment_sources" api:"required"`
	// When the role was created.
	CreatedAt int64 `json:"created_at" api:"required" format:"unixtime"`
	// Identifier of the actor who created the role.
	CreatedBy string `json:"created_by" api:"required"`
	// User details for the actor that created the role, when available.
	CreatedByUserObj map[string]any `json:"created_by_user_obj" api:"required"`
	// Description of the role.
	Description string `json:"description" api:"required"`
	// Arbitrary metadata stored on the role.
	Metadata map[string]any `json:"metadata" api:"required"`
	// Name of the role.
	Name string `json:"name" api:"required"`
	// Permissions associated with the role.
	Permissions []string `json:"permissions" api:"required"`
	// Whether the role is predefined by OpenAI.
	PredefinedRole bool `json:"predefined_role" api:"required"`
	// Resource type the role applies to.
	ResourceType string `json:"resource_type" api:"required"`
	// When the role was last updated.
	UpdatedAt int64 `json:"updated_at" api:"required" format:"unixtime"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ID                respjson.Field
		AssignmentSources respjson.Field
		CreatedAt         respjson.Field
		CreatedBy         respjson.Field
		CreatedByUserObj  respjson.Field
		Description       respjson.Field
		Metadata          respjson.Field
		Name              respjson.Field
		Permissions       respjson.Field
		PredefinedRole    respjson.Field
		ResourceType      respjson.Field
		UpdatedAt         respjson.Field
		ExtraFields       map[string]respjson.Field
		raw               string
	} `json:"-"`
}

// Returns the unmodified JSON received from the API
func (r AdminOrganizationProjectUserRoleGetResponse) RawJSON() string { return r.JSON.raw }
func (r *AdminOrganizationProjectUserRoleGetResponse) UnmarshalJSON(data []byte) error {
	return apijson.UnmarshalRoot(data, r)
}

type AdminOrganizationProjectUserRoleGetResponseAssignmentSource struct {
	PrincipalID   string `json:"principal_id" api:"required"`
	PrincipalType string `json:"principal_type" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		PrincipalID   respjson.Field
		PrincipalType respjson.Field
		ExtraFields   map[string]respjson.Field
		raw           string
	} `json:"-"`
}

// Returns the unmodified JSON received from the API
func (r AdminOrganizationProjectUserRoleGetResponseAssignmentSource) RawJSON() string {
	return r.JSON.raw
}
func (r *AdminOrganizationProjectUserRoleGetResponseAssignmentSource) UnmarshalJSON(data []byte) error {
	return apijson.UnmarshalRoot(data, r)
}

// Detailed information about a role assignment entry returned when listing
// assignments.
type AdminOrganizationProjectUserRoleListResponse struct {
	// Identifier for the role.
	ID string `json:"id" api:"required"`
	// Principals from which the role assignment is inherited, when available.
	AssignmentSources []AdminOrganizationProjectUserRoleListResponseAssignmentSource `json:"assignment_sources" api:"required"`
	// When the role was created.
	CreatedAt int64 `json:"created_at" api:"required" format:"unixtime"`
	// Identifier of the actor who created the role.
	CreatedBy string `json:"created_by" api:"required"`
	// User details for the actor that created the role, when available.
	CreatedByUserObj map[string]any `json:"created_by_user_obj" api:"required"`
	// Description of the role.
	Description string `json:"description" api:"required"`
	// Arbitrary metadata stored on the role.
	Metadata map[string]any `json:"metadata" api:"required"`
	// Name of the role.
	Name string `json:"name" api:"required"`
	// Permissions associated with the role.
	Permissions []string `json:"permissions" api:"required"`
	// Whether the role is predefined by OpenAI.
	PredefinedRole bool `json:"predefined_role" api:"required"`
	// Resource type the role applies to.
	ResourceType string `json:"resource_type" api:"required"`
	// When the role was last updated.
	UpdatedAt int64 `json:"updated_at" api:"required" format:"unixtime"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ID                respjson.Field
		AssignmentSources respjson.Field
		CreatedAt         respjson.Field
		CreatedBy         respjson.Field
		CreatedByUserObj  respjson.Field
		Description       respjson.Field
		Metadata          respjson.Field
		Name              respjson.Field
		Permissions       respjson.Field
		PredefinedRole    respjson.Field
		ResourceType      respjson.Field
		UpdatedAt         respjson.Field
		ExtraFields       map[string]respjson.Field
		raw               string
	} `json:"-"`
}

// Returns the unmodified JSON received from the API
func (r AdminOrganizationProjectUserRoleListResponse) RawJSON() string { return r.JSON.raw }
func (r *AdminOrganizationProjectUserRoleListResponse) UnmarshalJSON(data []byte) error {
	return apijson.UnmarshalRoot(data, r)
}

type AdminOrganizationProjectUserRoleListResponseAssignmentSource struct {
	PrincipalID   string `json:"principal_id" api:"required"`
	PrincipalType string `json:"principal_type" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		PrincipalID   respjson.Field
		PrincipalType respjson.Field
		ExtraFields   map[string]respjson.Field
		raw           string
	} `json:"-"`
}

// Returns the unmodified JSON received from the API
func (r AdminOrganizationProjectUserRoleListResponseAssignmentSource) RawJSON() string {
	return r.JSON.raw
}
func (r *AdminOrganizationProjectUserRoleListResponseAssignmentSource) UnmarshalJSON(data []byte) error {
	return apijson.UnmarshalRoot(data, r)
}

// Confirmation payload returned after unassigning a role.
type AdminOrganizationProjectUserRoleDeleteResponse struct {
	// Whether the assignment was removed.
	Deleted bool `json:"deleted" api:"required"`
	// Identifier for the deleted assignment, such as `group.role.deleted` or
	// `user.role.deleted`.
	Object string `json:"object" api:"required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Deleted     respjson.Field
		Object      respjson.Field
		ExtraFields map[string]respjson.Field
		raw         string
	} `json:"-"`
}

// Returns the unmodified JSON received from the API
func (r AdminOrganizationProjectUserRoleDeleteResponse) RawJSON() string { return r.JSON.raw }
func (r *AdminOrganizationProjectUserRoleDeleteResponse) UnmarshalJSON(data []byte) error {
	return apijson.UnmarshalRoot(data, r)
}

type AdminOrganizationProjectUserRoleNewParams struct {
	// Identifier of the role to assign.
	RoleID string `json:"role_id" api:"required"`
	paramObj
}

func (r AdminOrganizationProjectUserRoleNewParams) MarshalJSON() (data []byte, err error) {
	type shadow AdminOrganizationProjectUserRoleNewParams
	return param.MarshalObject(r, (*shadow)(&r))
}
func (r *AdminOrganizationProjectUserRoleNewParams) UnmarshalJSON(data []byte) error {
	return apijson.UnmarshalRoot(data, r)
}

type AdminOrganizationProjectUserRoleListParams struct {
	// Cursor for pagination. Provide the value from the previous response's `next`
	// field to continue listing project roles.
	After param.Opt[string] `query:"after,omitzero" json:"-"`
	// A limit on the number of project role assignments to return.
	Limit param.Opt[int64] `query:"limit,omitzero" json:"-"`
	// Sort order for the returned project roles.
	//
	// Any of "asc", "desc".
	Order AdminOrganizationProjectUserRoleListParamsOrder `query:"order,omitzero" json:"-"`
	paramObj
}

// URLQuery serializes [AdminOrganizationProjectUserRoleListParams]'s query
// parameters as `url.Values`.
func (r AdminOrganizationProjectUserRoleListParams) URLQuery() (v url.Values, err error) {
	return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{
		ArrayFormat:  apiquery.ArrayQueryFormatBrackets,
		NestedFormat: apiquery.NestedQueryFormatBrackets,
	})
}

// Sort order for the returned project roles.
type AdminOrganizationProjectUserRoleListParamsOrder string

const (
	AdminOrganizationProjectUserRoleListParamsOrderAsc  AdminOrganizationProjectUserRoleListParamsOrder = "asc"
	AdminOrganizationProjectUserRoleListParamsOrderDesc AdminOrganizationProjectUserRoleListParamsOrder = "desc"
)
