package service

import (
	"context"

	"wucher/internal/domain/federal_state"
	"wucher/internal/shared/pkg/sortkey"
)

type FederalStateService struct {
	repo federal_state.Repository
}

func NewFederalStateService(repo federal_state.Repository) *FederalStateService {
	return &FederalStateService{repo: repo}
}

func (s *FederalStateService) Create(ctx context.Context, row *federal_state.FederalState) error {
	return s.repo.Create(ctx, row)
}

func (s *FederalStateService) Update(ctx context.Context, row *federal_state.FederalState) error {
	return s.repo.Update(ctx, row)
}

func (s *FederalStateService) Delete(ctx context.Context, id []byte, deletedBy []byte) error {
	return s.repo.Delete(ctx, id, deletedBy)
}

func (s *FederalStateService) GetByID(ctx context.Context, id []byte) (*federal_state.FederalState, error) {
	return s.repo.GetByID(ctx, id)
}

func (s *FederalStateService) List(ctx context.Context, filter, sort string, limit, offset int, landID []byte, landName string) ([]federal_state.FederalState, int64, error) {
	return s.repo.List(ctx, filter, normalizeFederalStateSort(sort), limit, offset, landID, landName)
}

func normalizeFederalStateSort(sort string) string {
	return normalizeSortByRules(sort,
		sortExpr(
			joinSortClauses(sortkey.ActivePositiveSortClauses("", "is_active", "sortkey", "name", false)),
			joinSortClauses(sortkey.ActivePositiveSortClauses("", "is_active", "sortkey", "name", true)),
			"sortkey",
		),
		sortField("name"),
		sortField("sortkey", "sortkey", "sort_key"),
		sortField("is_active"),
		sortField("created_at"),
		sortField("updated_at"),
	)
}
