// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.

package provider

import (
	"context"
	"fmt"
	tfTypes "github.com/airbytehq/terraform-provider-airbyte/internal/provider/types"
	"github.com/airbytehq/terraform-provider-airbyte/internal/sdk"
	"github.com/airbytehq/terraform-provider-airbyte/internal/sdk/models/operations"
	"github.com/hashicorp/terraform-plugin-framework/datasource"
	"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
	"github.com/hashicorp/terraform-plugin-framework/types"
	"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
)

// Ensure provider defined types fully satisfy framework interfaces.
var _ datasource.DataSource = &ConnectionsDataSource{}
var _ datasource.DataSourceWithConfigure = &ConnectionsDataSource{}

func NewConnectionsDataSource() datasource.DataSource {
	return &ConnectionsDataSource{}
}

// ConnectionsDataSource is the data source implementation.
type ConnectionsDataSource struct {
	client *sdk.SDK
}

// ConnectionsDataSourceModel describes the data model.
type ConnectionsDataSourceModel struct {
	Data           []tfTypes.ConnectionResponse `tfsdk:"data"`
	IncludeDeleted types.Bool                   `queryParam:"style=form,explode=true,name=includeDeleted" tfsdk:"include_deleted"`
	Limit          types.Int32                  `queryParam:"style=form,explode=true,name=limit" tfsdk:"limit"`
	Next           types.String                 `tfsdk:"next"`
	Offset         types.Int32                  `queryParam:"style=form,explode=true,name=offset" tfsdk:"offset"`
	Previous       types.String                 `tfsdk:"previous"`
	TagIds         []types.String               `queryParam:"style=form,explode=true,name=tagIds" tfsdk:"tag_ids"`
	WorkspaceIds   []types.String               `queryParam:"style=form,explode=true,name=workspaceIds" tfsdk:"workspace_ids"`
}

// Metadata returns the data source type name.
func (r *ConnectionsDataSource) Metadata(ctx context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
	resp.TypeName = req.ProviderTypeName + "_connections"
}

// Schema defines the schema for the data source.
func (r *ConnectionsDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) {
	resp.Schema = schema.Schema{
		MarkdownDescription: "Connections DataSource",

		Attributes: map[string]schema.Attribute{
			"data": schema.ListNestedAttribute{
				Computed: true,
				NestedObject: schema.NestedAttributeObject{
					Attributes: map[string]schema.Attribute{
						"configurations": schema.SingleNestedAttribute{
							Computed: true,
							Attributes: map[string]schema.Attribute{
								"streams": schema.SetNestedAttribute{
									Computed: true,
									NestedObject: schema.NestedAttributeObject{
										Attributes: map[string]schema.Attribute{
											"cursor_field": schema.ListAttribute{
												Computed:    true,
												ElementType: types.StringType,
												Description: `Path to the field that will be used to determine if a record is new or modified since the last sync. This field is REQUIRED if ` + "`" + `sync_mode` + "`" + ` is ` + "`" + `incremental` + "`" + ` unless there is a default.`,
											},
											"destination_object_name": schema.StringAttribute{
												Computed:    true,
												Description: `The name of the destination object that this stream will be written to, used for data activation destinations.`,
											},
											"include_files": schema.BoolAttribute{
												Computed:    true,
												Description: `Whether to move raw files from the source to the destination during the sync.`,
											},
											"mappers": schema.ListNestedAttribute{
												Computed: true,
												NestedObject: schema.NestedAttributeObject{
													Attributes: map[string]schema.Attribute{
														"id": schema.StringAttribute{
															Computed: true,
														},
														"mapper_configuration": schema.SingleNestedAttribute{
															Computed: true,
															Attributes: map[string]schema.Attribute{
																"encryption": schema.SingleNestedAttribute{
																	Computed: true,
																	Attributes: map[string]schema.Attribute{
																		"aes": schema.SingleNestedAttribute{
																			Computed: true,
																			Attributes: map[string]schema.Attribute{
																				"algorithm": schema.StringAttribute{
																					Computed: true,
																				},
																				"field_name_suffix": schema.StringAttribute{
																					Computed: true,
																				},
																				"key": schema.StringAttribute{
																					Computed:  true,
																					Sensitive: true,
																				},
																				"mode": schema.StringAttribute{
																					Computed: true,
																				},
																				"padding": schema.StringAttribute{
																					Computed: true,
																				},
																				"target_field": schema.StringAttribute{
																					Computed: true,
																				},
																			},
																		},
																		"rsa": schema.SingleNestedAttribute{
																			Computed: true,
																			Attributes: map[string]schema.Attribute{
																				"algorithm": schema.StringAttribute{
																					Computed: true,
																				},
																				"field_name_suffix": schema.StringAttribute{
																					Computed: true,
																				},
																				"public_key": schema.StringAttribute{
																					Computed: true,
																				},
																				"target_field": schema.StringAttribute{
																					Computed: true,
																				},
																			},
																		},
																	},
																},
																"field_renaming": schema.SingleNestedAttribute{
																	Computed: true,
																	Attributes: map[string]schema.Attribute{
																		"new_field_name": schema.StringAttribute{
																			Computed:    true,
																			Description: `The new name for the field after renaming.`,
																		},
																		"original_field_name": schema.StringAttribute{
																			Computed:    true,
																			Description: `The current name of the field to rename.`,
																		},
																	},
																},
																"hashing": schema.SingleNestedAttribute{
																	Computed: true,
																	Attributes: map[string]schema.Attribute{
																		"field_name_suffix": schema.StringAttribute{
																			Computed:    true,
																			Description: `The suffix to append to the field name after hashing.`,
																		},
																		"method": schema.StringAttribute{
																			Computed:    true,
																			Description: `The hashing algorithm to use.`,
																		},
																		"target_field": schema.StringAttribute{
																			Computed:    true,
																			Description: `The name of the field to be hashed.`,
																		},
																	},
																},
																"row_filtering": schema.SingleNestedAttribute{
																	Computed: true,
																	Attributes: map[string]schema.Attribute{
																		"conditions": schema.StringAttribute{
																			Computed:    true,
																			Description: `Parsed as JSON.`,
																		},
																	},
																},
															},
															Description: `The values required to configure the mapper.`,
														},
														"type": schema.StringAttribute{
															Computed: true,
														},
													},
												},
												Description: `Mappers that should be applied to the stream before writing to the destination.`,
											},
											"name": schema.StringAttribute{
												Computed: true,
											},
											"namespace": schema.StringAttribute{
												Computed:    true,
												Description: `Namespace of the stream.`,
											},
											"primary_key": schema.ListAttribute{
												Computed: true,
												ElementType: types.ListType{
													ElemType: types.StringType,
												},
												Description: `Paths to the fields that will be used as primary key. This field is REQUIRED if ` + "`" + `destination_sync_mode` + "`" + ` is ` + "`" + `*_dedup` + "`" + ` unless it is already supplied by the source schema.`,
											},
											"selected_fields": schema.ListNestedAttribute{
												Computed: true,
												NestedObject: schema.NestedAttributeObject{
													Attributes: map[string]schema.Attribute{
														"field_path": schema.ListAttribute{
															Computed:    true,
															ElementType: types.StringType,
														},
													},
												},
												Description: `Paths to the fields that will be included in the configured catalog.`,
											},
											"sync_mode": schema.StringAttribute{
												Computed: true,
											},
										},
									},
								},
							},
							Description: `A list of configured stream options for a connection.`,
						},
						"connection_id": schema.StringAttribute{
							Computed: true,
						},
						"created_at": schema.Int64Attribute{
							Computed: true,
						},
						"destination_id": schema.StringAttribute{
							Computed: true,
						},
						"name": schema.StringAttribute{
							Computed: true,
						},
						"namespace_definition": schema.StringAttribute{
							Computed:    true,
							Description: `Define the location where the data will be stored in the destination`,
						},
						"namespace_format": schema.StringAttribute{
							Computed: true,
						},
						"non_breaking_schema_updates_behavior": schema.StringAttribute{
							Computed:    true,
							Description: `Set how Airbyte handles syncs when it detects a non-breaking schema change in the source`,
						},
						"prefix": schema.StringAttribute{
							Computed: true,
						},
						"schedule": schema.SingleNestedAttribute{
							Computed: true,
							Attributes: map[string]schema.Attribute{
								"basic_timing": schema.StringAttribute{
									Computed: true,
								},
								"cron_expression": schema.StringAttribute{
									Computed: true,
								},
								"schedule_type": schema.StringAttribute{
									Computed: true,
								},
							},
							Description: `schedule for when the the connection should run, per the schedule type`,
						},
						"source_id": schema.StringAttribute{
							Computed: true,
						},
						"status": schema.StringAttribute{
							Computed: true,
						},
						"tags": schema.ListNestedAttribute{
							Computed: true,
							NestedObject: schema.NestedAttributeObject{
								Attributes: map[string]schema.Attribute{
									"color": schema.StringAttribute{
										Computed: true,
									},
									"name": schema.StringAttribute{
										Computed: true,
									},
									"tag_id": schema.StringAttribute{
										Computed: true,
									},
									"workspace_id": schema.StringAttribute{
										Computed: true,
									},
								},
							},
						},
						"workspace_id": schema.StringAttribute{
							Computed: true,
						},
					},
				},
			},
			"include_deleted": schema.BoolAttribute{
				Optional:    true,
				Description: `Include deleted connections in the returned results.`,
			},
			"limit": schema.Int32Attribute{
				Optional:    true,
				Description: `Set the limit on the number of Connections returned. The default is 20.`,
			},
			"next": schema.StringAttribute{
				Computed: true,
			},
			"offset": schema.Int32Attribute{
				Optional:    true,
				Description: `Set the offset to start at when returning Connections. The default is 0`,
			},
			"previous": schema.StringAttribute{
				Computed: true,
			},
			"tag_ids": schema.ListAttribute{
				Optional:    true,
				ElementType: types.StringType,
				Description: `The UUIDs of the tags you wish to list connections for. Empty list will retrieve all connections.`,
			},
			"workspace_ids": schema.ListAttribute{
				Optional:    true,
				ElementType: types.StringType,
				Description: `The UUIDs of the workspaces you wish to list connections for. Empty list will retrieve all allowed workspaces.`,
			},
		},
	}
}

func (r *ConnectionsDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
	// Prevent panic if the provider has not been configured.
	if req.ProviderData == nil {
		return
	}

	client, ok := req.ProviderData.(*sdk.SDK)

	if !ok {
		resp.Diagnostics.AddError(
			"Unexpected DataSource Configure Type",
			fmt.Sprintf("Expected *sdk.SDK, got: %T. Please report this issue to the provider developers.", req.ProviderData),
		)

		return
	}

	r.client = client
}

func (r *ConnectionsDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
	var data *ConnectionsDataSourceModel
	var item types.Object

	resp.Diagnostics.Append(req.Config.Get(ctx, &item)...)
	if resp.Diagnostics.HasError() {
		return
	}

	resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{
		UnhandledNullAsEmpty:    true,
		UnhandledUnknownAsEmpty: true,
	})...)

	if resp.Diagnostics.HasError() {
		return
	}

	var workspaceIds []string = []string{}
	for _, workspaceIdsItem := range data.WorkspaceIds {
		workspaceIds = append(workspaceIds, workspaceIdsItem.ValueString())
	}
	var tagIds []string = []string{}
	for _, tagIdsItem := range data.TagIds {
		tagIds = append(tagIds, tagIdsItem.ValueString())
	}
	includeDeleted := new(bool)
	if !data.IncludeDeleted.IsUnknown() && !data.IncludeDeleted.IsNull() {
		*includeDeleted = data.IncludeDeleted.ValueBool()
	} else {
		includeDeleted = nil
	}
	limit := new(int)
	if !data.Limit.IsUnknown() && !data.Limit.IsNull() {
		*limit = int(data.Limit.ValueInt32())
	} else {
		limit = nil
	}
	offset := new(int)
	if !data.Offset.IsUnknown() && !data.Offset.IsNull() {
		*offset = int(data.Offset.ValueInt32())
	} else {
		offset = nil
	}
	request := operations.ListConnectionsRequest{
		WorkspaceIds:   workspaceIds,
		TagIds:         tagIds,
		IncludeDeleted: includeDeleted,
		Limit:          limit,
		Offset:         offset,
	}
	res, err := r.client.Connections.ListConnections(ctx, request)
	if err != nil {
		resp.Diagnostics.AddError("failure to invoke API", err.Error())
		if res != nil && res.RawResponse != nil {
			resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse))
		}
		return
	}
	if res == nil {
		resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res))
		return
	}
	if res.StatusCode == 404 {
		resp.State.RemoveResource(ctx)
		return
	}
	if res.StatusCode != 200 {
		resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse))
		return
	}
	if !(res.ConnectionsResponse != nil) {
		resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse))
		return
	}
	data.RefreshFromSharedConnectionsResponse(res.ConnectionsResponse)

	// Save updated data into Terraform state
	resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
