package bservice

import (
	"context"
	"strconv"

	"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
	"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                = &resourceBService{}
	_ resource.ResourceWithImportState = &resourceBService{}
)

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

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

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

	contextCreateMap := map[string]any{
		"name":  plan.Name.ValueString(),
		"rg_id": plan.RGID.ValueInt64(),
	}
	tflog.Info(ctx, "Create resourceBService: got plan successfully", contextCreateMap)
	tflog.Info(ctx, "Create resourceBService: 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 resourceBService: Error set timeout")
		return
	}
	tflog.Info(ctx, "Create resourceBService: set timeouts successfully", map[string]any{
		"name":          plan.Name.ValueString(),
		"rg_id":         plan.RGID.ValueInt64(),
		"createTimeout": createTimeout})

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

	if len(plan.Snapshots.Elements()) > 0 {
		resp.Diagnostics.AddError("BServiceResourceCreate: snapshot field must be empty when resource is creating", "")
		return
	}

	// Make create request and get response
	id, diags := utilities.BServiceResourceCreate(ctx, &plan, r.client)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		return
	}
	plan.ID = types.StringValue(strconv.Itoa(int(*id)))
	tflog.Info(ctx, "BServiceResourceCreate: BService created", map[string]any{"service_id": id})

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

	// Map response body to schema and populate Computed attribute values
	resp.Diagnostics.Append(flattens.BServiceResource(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 *resourceBService) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
	// Get current state
	var state models.RecordBasicServiceResourceModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceBService: Error get state")
		return
	}
	tflog.Info(ctx, "Read resourceBService: 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 resourceBService: Error set timeout")
		return
	}
	tflog.Info(ctx, "Read resourceBService: 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.BSerivceReadStatus(ctx, &state, r.client)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceBService: Error reading status")
		return
	}

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

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

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

	logMap := map[string]any{"service_id": plan.ID.ValueString()}
	tflog.Info(ctx, "Update resourceBService: got plan successfully", logMap)

	// Retrieve values from state
	var state models.RecordBasicServiceResourceModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Update resourceBService: Error receiving the state")
		return
	}
	tflog.Info(ctx, "Update resourceBService: 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 resourceBService: Error set timeout")
		return
	}
	tflog.Info(ctx, "Update resourceBService: set timeouts successfully", map[string]any{
		"service_id":    state.ID.ValueString(),
		"updateTimeout": updateTimeout})

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

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

	// enable/disable bservice
	if !plan.Enable.Equal(state.Enable) && !plan.Enable.IsNull() {
		resp.Diagnostics.Append(utilities.EnableDisableBService(ctx, &plan, r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceBService: Error enabling/disabling bservice")
			return
		}
	}

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

	// SnapshotsBService bservice
	if !plan.Snapshots.Equal(state.Snapshots) && !plan.Snapshots.IsNull() {
		resp.Diagnostics.Append(utilities.SnapshotsBService(ctx, state.Snapshots, plan.Snapshots, uint64(state.ServiceId.ValueInt64()), r.client)...)
		if resp.Diagnostics.HasError() {
			tflog.Error(ctx, "Update resourceBService: Error snapshosts bservice")
			return
		}
	}

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

	// Map response body to schema and populate Computed attribute values
	resp.Diagnostics.Append(flattens.BServiceResource(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 *resourceBService) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
	// Get current state
	var state models.RecordBasicServiceResourceModel

	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Delete resourceBService: Error get state")
		return
	}
	tflog.Info(ctx, "Delete resourceBService: 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 resourceBService: Error set timeout")
		return
	}
	tflog.Info(ctx, "Delete resourceBService: set timeouts successfully", map[string]any{
		"service_id":    state.ID.ValueString(),
		"deleteTimeout": deleteTimeout})

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

	permanently := state.Permanently.ValueBool()
	if state.Permanently.IsNull() {
		permanently = true
	} // default true

	// Delete existing resource group
	delReq := bservice.DeleteRequest{
		ServiceID:   uint64(state.ServiceId.ValueInt64()),
		Permanently: permanently,
	}

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

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

// Schema defines the schema for the resource.
func (r *resourceBService) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
	resp.Schema = schema.Schema{
		Attributes: schemas.MakeSchemaResourceBService(),
		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 *resourceBService) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
	resp.TypeName = req.ProviderTypeName + "_bservice"
}

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

func (r *resourceBService) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
	// Retrieve import ID and save to id attribute
	resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
}
