package bservice

import (
	"context"
	"fmt"
	"strconv"
	"strings"

	"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
	"github.com/hashicorp/terraform-plugin-framework/attr"
	"github.com/hashicorp/terraform-plugin-framework/path"
	"github.com/hashicorp/terraform-plugin-framework/resource"
	"github.com/hashicorp/terraform-plugin-framework/resource/schema"
	"github.com/hashicorp/terraform-plugin-framework/types"
	"github.com/hashicorp/terraform-plugin-log/tflog"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/bservice"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/constants"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/bservice/flattens"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/bservice/models"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/bservice/schemas"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/bservice/utilities"
)

// Ensure the implementation satisfies the expected interfaces.
var (
	_ resource.Resource                = &resourceBServiceGroup{}
	_ resource.ResourceWithImportState = &resourceBServiceGroup{}
)

// NewResourceBServiceGroup is a helper function to simplify the provider implementation.
func NewResourceBServiceGroup() resource.Resource {
	return &resourceBServiceGroup{}
}

// resourceBServiceGroup is the resource implementation.
type resourceBServiceGroup struct {
	client *client.Client
}

// Create creates the resource and sets the initial Terraform state.
func (r *resourceBServiceGroup) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
	// Get plan to create resource group
	var plan models.ResourceRecordGroupModel
	resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Create resourceBServiceGroup: Error receiving the plan")
		return
	}

	contextCreateMap := map[string]any{
		"service_id":   plan.ServiceID.ValueInt64(),
		"compgroup_id": plan.CompgroupID.ValueInt64(),
	}
	tflog.Info(ctx, "Create resourceBServiceGroup: got plan successfully", contextCreateMap)
	tflog.Info(ctx, "Create resourceBServiceGroup: start creating", contextCreateMap)

	// Set timeouts
	createTimeout, diags := plan.Timeouts.Create(ctx, constants.Timeout600s)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Create resourceBServiceGroup: Error set timeout")
		return
	}
	tflog.Info(ctx, "Create resourceBServiceGroup: set timeouts successfully", map[string]any{
		"service_id":    plan.ServiceID.ValueInt64(),
		"compgroup_id":  plan.CompgroupID.ValueInt64(),
		"createTimeout": createTimeout})

	ctx, cancel := context.WithTimeout(ctx, createTimeout)
	defer cancel()

	// Check if input values are valid in the platform
	tflog.Info(ctx, "Create resourceBServiceGroup: starting input checks", map[string]any{"name": plan.Name.ValueString()})
	resp.Diagnostics.Append(resourceBServiceGroupInputCheck(ctx, &plan, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Create resourceBServiceGroup: Error input checks")
		return
	}
	tflog.Info(ctx, "Create resourceBServiceGroup: input checks successful", map[string]any{"name": plan.Name.ValueString()})

	// Make create request and get response
	diags = utilities.BServiceGroupResourceCreate(ctx, &plan, r.client)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		return
	}
	tflog.Info(ctx, "BServiceResourceCreate: BService group created", map[string]any{"service_id": plan.ServiceID.ValueInt64()})

	if !plan.Parents.IsNull() {
		oldParents := types.ListValueMust(
			types.Int64Type,
			[]attr.Value{},
		)
		resp.Diagnostics.Append(utilities.BServiceGroupParents(ctx, plan.Parents, oldParents, &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			return
		}
	}

	tflog.Info(ctx, "BServiceResourceCreate: resource creation is completed", map[string]any{"service_id": plan.ServiceID.ValueInt64()})

	// Map response body to schema and populate Computed attribute values
	resp.Diagnostics.Append(flattens.BServiceGroupResource(ctx, &plan, r.client)...)
	if resp.Diagnostics.HasError() {
		return
	}

	// Set state to fully populated data
	resp.Diagnostics.Append(resp.State.Set(ctx, plan)...)
	if resp.Diagnostics.HasError() {
		return
	}
}

// Read refreshes the Terraform state with the latest data.
func (r *resourceBServiceGroup) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
	// Get current state
	var state models.ResourceRecordGroupModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceBServiceGroup: Error get state")
		return
	}
	tflog.Info(ctx, "Read resourceBServiceGroup: got state successfully", map[string]any{"service_id": state.ID.ValueString()})

	// Set timeouts
	readTimeout, diags := state.Timeouts.Read(ctx, constants.Timeout300s)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceBServiceGroup: Error set timeout")
		return
	}
	tflog.Info(ctx, "Read resourceBServiceGroup: set timeouts successfully", map[string]any{
		"service_id":  state.ID.ValueString(),
		"readTimeout": readTimeout})

	ctx, cancel := context.WithTimeout(ctx, readTimeout)
	defer cancel()

	// read status
	resp.Diagnostics.Append(utilities.BServiceGroupReadStatus(ctx, &state, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceBServiceGroup: Error reading status")
		return
	}

	// Overwrite items with refreshed state
	resp.Diagnostics.Append(flattens.BServiceGroupResource(ctx, &state, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceBServiceGroup: Error flatten")
		return
	}

	// Set refreshed state
	resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceBServiceGroup: Error set state")
		return
	}
	tflog.Info(ctx, "End read resourceBServiceGroup")
}

// Update updates the resource and sets the updated Terraform state on success.
func (r *resourceBServiceGroup) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
	// Retrieve values from plan
	var plan models.ResourceRecordGroupModel
	resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Update resourceBServiceGroup: Error receiving the plan")
		return
	}

	tflog.Info(ctx, "Update resourceBServiceGroup: got plan successfully", map[string]any{"compgroup_name": plan.Name.ValueString()})

	// Retrieve values from state
	var state models.ResourceRecordGroupModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Update resourceBServiceGroup: Error receiving the state")
		return
	}
	logMap := map[string]any{"service_id": state.ID.ValueString()}
	tflog.Info(ctx, "Update resourceBServiceGroup: got state successfully", logMap)

	// Set timeouts
	updateTimeout, diags := plan.Timeouts.Update(ctx, constants.Timeout300s)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Update resourceBServiceGroup: Error set timeout")
		return
	}
	tflog.Info(ctx, "Update resourceBServiceGroup: set timeouts successfully", map[string]any{
		"service_id":    state.ID.ValueString(),
		"updateTimeout": updateTimeout})

	ctx, cancel := context.WithTimeout(ctx, updateTimeout)
	defer cancel()

	// Check if input values are valid in the platform
	tflog.Info(ctx, "Create resourceBServiceGroup: starting input checks", map[string]any{"name": plan.Name.ValueString()})
	resp.Diagnostics.Append(resourceBServiceGroupInputCheck(ctx, &plan, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Create resourceBServiceGroup: Error input checks")
		return
	}
	tflog.Info(ctx, "Create resourceBServiceGroup: input checks successful", map[string]any{"name": plan.Name.ValueString()})

	_, err := strconv.Atoi(state.ID.ValueString())
	if err != nil {
		resp.Diagnostics.AddError("Update resourceBServiceGroup: Cannot parse ID from state", err.Error())
		return
	}

	plan.ID = state.ID

	if !plan.CompCount.Equal(state.CompCount) && !plan.CompCount.IsNull() {
		resp.Diagnostics.Append(utilities.BServiceGroupResize(ctx, &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceBServiceGroup: Error enabling/disabling bservice")
			return
		}
	}

	if !plan.Start.Equal(state.Start) && !plan.Start.IsNull() {
		resp.Diagnostics.Append(utilities.BServiceGroupStartStop(ctx, &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceBServiceGroup: Error start/stop bservice")
			return
		}
	}

	if !plan.Name.Equal(state.Name) || !plan.RAM.Equal(state.RAM) || !plan.CPU.Equal(state.CPU) || !plan.Disk.Equal(state.Disk) || (!plan.Role.Equal(state.Role) && !plan.Role.IsUnknown()) {
		resp.Diagnostics.Append(utilities.BServiceGroupUpdate(ctx, &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceBServiceGroup: Error update bservice group")
			return
		}
	}

	if !plan.ExtNets.Equal(state.ExtNets) && !plan.ExtNets.IsUnknown() {
		resp.Diagnostics.Append(utilities.BServiceGroupExtNet(ctx, &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceBServiceGroup: Error update extnets bservice")
			return
		}
	}

	if !plan.VINSes.Equal(state.VINSes) && !plan.VINSes.IsUnknown() {
		resp.Diagnostics.Append(utilities.BServiceGroupVinses(ctx, &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceBServiceGroup: Error update vinses bservice")
			return
		}
	}

	if !plan.Parents.Equal(state.Parents) && !plan.Parents.IsNull() {
		resp.Diagnostics.Append(utilities.BServiceGroupParents(ctx, plan.Parents, state.Parents, &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceBServiceGroup: Error update parents bservice")
			return
		}
	}

	if !plan.RemoveComputes.Equal(state.RemoveComputes) && !plan.RemoveComputes.IsNull() {
		resp.Diagnostics.Append(utilities.BServiceGroupRemoveComputes(ctx, &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceBServiceGroup: Error remove computes bservice")
			return
		}
	}

	tflog.Info(ctx, "Update resourceBServiceGroup: bservice update is completed", logMap)

	// Map response body to schema and populate Computed attribute values
	resp.Diagnostics.Append(flattens.BServiceGroupResource(ctx, &plan, r.client)...)
	if resp.Diagnostics.HasError() {
		return
	}

	// Set state to fully populated data
	resp.Diagnostics.Append(resp.State.Set(ctx, plan)...)
	if resp.Diagnostics.HasError() {
		return
	}
}

// Delete deletes the resource and removes the Terraform state on success.
func (r *resourceBServiceGroup) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
	// Get current state
	var state models.ResourceRecordGroupModel

	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Delete resourceBServiceGroup: Error get state")
		return
	}
	tflog.Info(ctx, "Delete resourceBServiceGroup: got state successfully", map[string]any{"serice_id": state.ID.ValueString()})

	// Set timeouts
	deleteTimeout, diags := state.Timeouts.Delete(ctx, constants.Timeout300s)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Delete resourceBServiceGroup: Error set timeout")
		return
	}
	tflog.Info(ctx, "Delete resourceBServiceGroup: set timeouts successfully", map[string]any{
		"service_id":    state.ID.ValueString(),
		"deleteTimeout": deleteTimeout})

	ctx, cancel := context.WithTimeout(ctx, deleteTimeout)
	defer cancel()

	// Delete existing resource group
	delReq := bservice.GroupRemoveRequest{
		ServiceID:   uint64(state.ServiceID.ValueInt64()),
		CompGroupID: uint64(state.CompgroupID.ValueInt64()),
	}

	tflog.Info(ctx, "Delete resourceBServiceGroup: before call CloudAPI().BService().GroupRemove", map[string]any{"req": delReq})
	_, err := r.client.CloudAPI().BService().GroupRemove(ctx, delReq)
	if err != nil {
		resp.Diagnostics.AddError("Delete resourceBServiceGroup: Error deleting BService group with error: ", err.Error())
		return
	}

	tflog.Info(ctx, "End delete resourceBServiceGroup", map[string]any{"service_id": state.ID.ValueString()})
}

// Schema defines the schema for the resource.
func (r *resourceBServiceGroup) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
	resp.Schema = schema.Schema{
		Attributes: schemas.MakeSchemaResourceBServiceGroup(),
		Blocks: map[string]schema.Block{
			"timeouts": timeouts.Block(ctx, timeouts.Opts{Create: true, Read: true, Update: true, Delete: true}),
		},
	}
}

// Metadata returns the resource type name.
func (r *resourceBServiceGroup) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
	resp.TypeName = req.ProviderTypeName + "_bservice_group"
}

// Configure adds the provider configured client to the resource.
func (r *resourceBServiceGroup) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
	tflog.Info(ctx, "Get Configure resourceBServiceGroup")
	r.client = client.Resource(ctx, &req, resp)
	tflog.Info(ctx, "Getting Configure resourceBServiceGroup successfully")
}

func (r *resourceBServiceGroup) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
	idParts := strings.Split(req.ID, "#")

	if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" {
		resp.Diagnostics.AddError(
			"Unexpected Import Identifier",
			fmt.Sprintf("Expected import identifier with format: service_id,compgroup_name. Got: %q", req.ID),
		)
		return
	}

	resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("sid"), idParts[0])...)
	resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), idParts[1])...)
}
