package platform

import (
	"context"
	"fmt"
	"strings"
)

func (s *Service) reconciliationStore() (ReconciliationStore, error) {
	store, ok := s.store.(ReconciliationStore)
	if !ok {
		return nil, fmt.Errorf("store does not provide reconciliation center")
	}
	return store, nil
}

func (s *Service) ReconciliationSummary(ctx context.Context, days int) (ReconciliationSummary, error) {
	store, err := s.reconciliationStore()
	if err != nil {
		return ReconciliationSummary{}, err
	}
	if days <= 0 || days > 90 {
		days = 30
	}
	return store.ReconciliationSummary(ctx, days)
}

func (s *Service) ReconciliationIssues(ctx context.Context, query ReconciliationQuery) (Page[ReconciliationIssue], error) {
	store, err := s.reconciliationStore()
	if err != nil {
		return Page[ReconciliationIssue]{}, err
	}
	query.Keyword = strings.TrimSpace(query.Keyword)
	query.RuleCode = strings.TrimSpace(query.RuleCode)
	query.Category = strings.TrimSpace(query.Category)
	query.Severity = strings.TrimSpace(query.Severity)
	query.Status = strings.TrimSpace(query.Status)
	if query.Limit <= 0 || query.Limit > 200 {
		query.Limit = 50
	}
	if query.Offset < 0 {
		query.Offset = 0
	}
	return store.ReconciliationIssues(ctx, query)
}

func (s *Service) ReconciliationIssue(ctx context.Context, id string) (ReconciliationIssue, error) {
	id = strings.TrimSpace(id)
	if id == "" || len(id) > 64 {
		return ReconciliationIssue{}, clientError{Code: "RECONCILIATION_ID_INVALID", Message: "差异记录编号无效"}
	}
	store, err := s.reconciliationStore()
	if err != nil {
		return ReconciliationIssue{}, err
	}
	return store.ReconciliationIssue(ctx, id)
}

func (s *Service) UpdateReconciliationIssue(ctx context.Context, id string, request ReconciliationActionRequest) (ReconciliationIssue, error) {
	id = strings.TrimSpace(id)
	if id == "" || len(id) > 64 {
		return ReconciliationIssue{}, clientError{Code: "RECONCILIATION_ID_INVALID", Message: "差异记录编号无效"}
	}
	request.Actor = ActorFromContext(ctx)
	store, err := s.reconciliationStore()
	if err != nil {
		return ReconciliationIssue{}, err
	}
	return store.UpdateReconciliationIssue(ctx, id, request)
}

func (s *Service) EvaluateReconciliation(ctx context.Context) (ReconciliationEvaluationResult, error) {
	store, err := s.reconciliationStore()
	if err != nil {
		return ReconciliationEvaluationResult{}, err
	}
	return store.EvaluateReconciliation(ctx)
}
