package provision

import (
	"context"
	"fmt"

	"sub2api-cn-relay-manager/internal/store/sqlite"
)

type BatchDetailResult struct {
	Batch            sqlite.ImportBatch
	Items            []sqlite.ImportBatchItem
	ManagedResources []sqlite.ManagedResource
	AccessClosures   []sqlite.AccessClosureRecord
	ReconcileRuns    []sqlite.ReconcileRun
}

type BatchDetailService struct {
	store *sqlite.DB
}

func NewBatchDetailService(store *sqlite.DB) *BatchDetailService {
	return &BatchDetailService{store: store}
}

func (s *BatchDetailService) Get(ctx context.Context, batchID int64) (BatchDetailResult, error) {
	if s == nil || s.store == nil {
		return BatchDetailResult{}, fmt.Errorf("store is required")
	}
	batch, err := s.store.ImportBatches().GetByID(ctx, batchID)
	if err != nil {
		return BatchDetailResult{}, err
	}
	items, err := s.store.ImportBatchItems().GetByBatchID(ctx, batchID)
	if err != nil {
		return BatchDetailResult{}, err
	}
	managedResources, err := s.store.ManagedResources().GetByBatchID(ctx, batchID)
	if err != nil {
		return BatchDetailResult{}, err
	}
	accessClosures, err := s.store.AccessClosures().GetByBatchID(ctx, batchID)
	if err != nil {
		return BatchDetailResult{}, err
	}
	reconcileRuns, err := s.store.ReconcileRuns().GetByBatchID(ctx, batchID)
	if err != nil {
		return BatchDetailResult{}, err
	}
	return BatchDetailResult{
		Batch:            batch,
		Items:            items,
		ManagedResources: managedResources,
		AccessClosures:   accessClosures,
		ReconcileRuns:    reconcileRuns,
	}, nil
}
