package vins

import (
	"context"
	"fmt"
	"time"

	"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/vins"
	"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/vins/flattens"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/vins/models"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/vins/schemas"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/vins/utilities"
)

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

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

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

// Create creates the resource and sets the initial Terraform state.
func (r *resourceVINSStaticRoute) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
	// Get plan to create vins
	var plan models.ResourceVINSStaticRouteModel
	resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Create resourceVINSStaticRoute: Error receiving the plan")
		return
	}
	tflog.Info(ctx, "Create resourceVINSStaticRoute: got plan successfully", map[string]any{"id": plan.Id.ValueString()})
	tflog.Info(ctx, "Create resourceVINSStaticRoute: start creating", map[string]any{"id": plan.Id.ValueString()})

	// Set timeouts
	createTimeout, diags := plan.Timeouts.Create(ctx, constants.Timeout20m)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Create resourceVINSStaticRoute: Error set timeout")
		return
	}
	tflog.Info(ctx, "Create resourceVINSStaticRoute: set timeouts successfully", map[string]any{
		"id":            plan.Id.ValueString(),
		"createTimeout": createTimeout})

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

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

	// Make create request and get response for vins static route creation
	staticReq := vins.StaticRouteAddRequest{
		VINSID:      uint64(plan.VinsID.ValueInt64()),
		Destination: plan.Destination.ValueString(),
		Netmask:     plan.Netmask.ValueString(),
		Gateway:     plan.Gateway.ValueString(),
	}

	_, err := r.client.CloudAPI().VINS().StaticRouteAdd(ctx, staticReq)
	if err != nil {
		resp.Diagnostics.AddError("Create resourceVINSStaticRoute: Error adding static route to vins", err.Error())
		return
	}

	routeId, diags := utilities.GetStaticRouteID(ctx, &plan, r.client)
	if diags.HasError() {
		resp.Diagnostics.Append(diags...)
		tflog.Error(ctx, "Create resourceVINSStaticRoute: cannot get route id")
		return
	}

	plan.Id = types.StringValue(fmt.Sprintf("%d#%d", plan.VinsID.ValueInt64(), routeId))

	tflog.Info(ctx, "Create resourceVINSStaticRoute: resource creation is completed", map[string]any{"id": plan.Id.ValueString()})

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

	plan.LastUpdated = types.StringValue(time.Now().Format(time.RFC850))

	// 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 *resourceVINSStaticRoute) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
	// Get current state
	var state models.ResourceVINSStaticRouteModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Read resourceVINSStaticRoute: Error get state")
		return
	}
	tflog.Info(ctx, "Read resourceVINSStaticRoute: got state successfully", map[string]any{"vins_id": state.Id.ValueString()})

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

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

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

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

// Update updates the resource and sets the updated Terraform state on success.
func (r *resourceVINSStaticRoute) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
	tflog.Error(ctx, "Update resourceVINSStaticRoute: This resource cannot be updated")
	resp.Diagnostics.AddError("This resource cannot be updated", "")
	return
}

// Delete deletes the resource and removes the Terraform state on success.
func (r *resourceVINSStaticRoute) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
	// Get current state
	var state models.ResourceVINSStaticRouteModel
	resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
	if resp.Diagnostics.HasError() {
		tflog.Error(ctx, "Delete resourceVINSStaticRoute: Error get state")
		return
	}
	tflog.Info(ctx, "Delete resourceVINSStaticRoute: got state successfully", map[string]any{"id": state.Id.ValueString()})

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

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

	vinsId, routeId, diags := utilities.GetVinsIDAndRouteID(ctx, &state)
	if diags.HasError() {
		resp.Diagnostics.Append(diags...)
		return
	}

	// Delete static route
	delReq := vins.StaticRouteDelRequest{
		VINSID:  vinsId,
		RouteId: routeId,
	}

	tflog.Info(ctx, "Delete resourceVINSStaticRoute: calling CloudAPI().VINS().StaticRouteDel", map[string]any{
		"id":  state.Id.ValueString(),
		"req": delReq,
	})
	_, err := r.client.CloudAPI().VINS().StaticRouteDel(ctx, delReq)
	if err != nil {
		resp.Diagnostics.AddError("Delete resourceVINSStaticRoute: Error deleting", err.Error())
		return
	}

	tflog.Info(ctx, "End delete resourceVINSStaticRoute", map[string]any{"id": state.Id.ValueString()})
}

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

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

func (r *resourceVINSStaticRoute) 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)
}
