package oci

import (
	"context"
	"fmt"
	"time"

	"github.com/oracle/oci-go-sdk/v65/common"
	"github.com/oracle/oci-go-sdk/v65/identity"
)

// Compartment 是租户下的一个 compartment（不含租户根本身）。
type Compartment struct {
	ID             string     `json:"id"`
	Name           string     `json:"name"`
	Description    string     `json:"description"`
	ParentID       string     `json:"parentId"`
	LifecycleState string     `json:"lifecycleState"`
	TimeCreated    *time.Time `json:"timeCreated"`
}

// ListCompartments 实现 Client：递归列出租户下全部 ACTIVE compartment。
func (c *RealClient) ListCompartments(ctx context.Context, cred Credentials) ([]Compartment, error) {
	ic, err := identity.NewIdentityClientWithConfigurationProvider(provider(cred))
	if err != nil {
		return nil, fmt.Errorf("new identity client: %w", err)
	}
	applyProxy(&ic.BaseClient, cred)
	var items []Compartment
	var page *string
	for {
		resp, err := ic.ListCompartments(ctx, identity.ListCompartmentsRequest{
			CompartmentId:          &cred.TenancyOCID,
			CompartmentIdInSubtree: common.Bool(true),
			AccessLevel:            identity.ListCompartmentsAccessLevelAny,
			LifecycleState:         identity.CompartmentLifecycleStateActive,
			Page:                   page,
		})
		if err != nil {
			return nil, fmt.Errorf("list compartments: %w", err)
		}
		for _, item := range resp.Items {
			items = append(items, toCompartment(item))
		}
		if resp.OpcNextPage == nil {
			return orEmpty(items), nil
		}
		page = resp.OpcNextPage
	}
}

func toCompartment(item identity.Compartment) Compartment {
	out := Compartment{
		ID:             deref(item.Id),
		Name:           deref(item.Name),
		Description:    deref(item.Description),
		ParentID:       deref(item.CompartmentId),
		LifecycleState: string(item.LifecycleState),
	}
	if item.TimeCreated != nil {
		out.TimeCreated = &item.TimeCreated.Time
	}
	return out
}
