package secgroup

import (
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/secgroup"
)

func flattenSecurityGroupResource(d *schema.ResourceData, securityGroup *secgroup.RecordSecurityGroup) {
	d.Set("security_group_id", securityGroup.ID)
	d.Set("account_id", securityGroup.AccountID)
	d.Set("name", securityGroup.Name)
	d.Set("description", securityGroup.Description)
	d.Set("rules", flattenRules(securityGroup.Rules))
	d.Set("created_at", securityGroup.CreatedAt)
	d.Set("created_by", securityGroup.CreatedBy)
	d.Set("updated_at", securityGroup.UpdatedAt)
	d.Set("updated_by", securityGroup.UpdatedBy)
}

func flattenSecurityGroupList(securityGroupList *secgroup.ListSecurityGroups) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(securityGroupList.Data))
	for _, v := range securityGroupList.Data {
		temp := map[string]interface{}{
			"account_id":        v.AccountID,
			"name":              v.Name,
			"description":       v.Description,
			"rules":             flattenRules(v.Rules),
			"created_at":        v.CreatedAt,
			"created_by":        v.CreatedBy,
			"security_group_id": v.ID,
			"updated_at":        v.UpdatedAt,
			"updated_by":        v.UpdatedBy,
		}

		res = append(res, temp)
	}

	return res
}

func flattenSecurityGroup(d *schema.ResourceData, securityGroup *secgroup.RecordSecurityGroup) {
	d.Set("security_group_id", securityGroup.ID)
	d.Set("account_id", securityGroup.AccountID)
	d.Set("name", securityGroup.Name)
	d.Set("description", securityGroup.Description)
	d.Set("rules", flattenRules(securityGroup.Rules))
	d.Set("created_at", securityGroup.CreatedAt)
	d.Set("created_by", securityGroup.CreatedBy)
	d.Set("updated_at", securityGroup.UpdatedAt)
	d.Set("updated_by", securityGroup.UpdatedBy)
}

func flattenRules(rules secgroup.Rules) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(rules))
	for _, rule := range rules {
		temp := map[string]interface{}{
			"id":               rule.ID,
			"direction":        rule.Direction,
			"ethertype":        rule.Ethertype,
			"protocol":         rule.Protocol,
			"port_range_min":   rule.PortRangeMin,
			"port_range_max":   rule.PortRangeMax,
			"remote_ip_prefix": rule.RemoteIPPrefix,
		}
		res = append(res, temp)
	}
	return res
}
