package service

import (
	"context"

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

type FacilityService struct {
	repo facility.Repository
}

func NewFacilityService(repo facility.Repository) *FacilityService {
	return &FacilityService{repo: repo}
}

func (s *FacilityService) Create(ctx context.Context, f *facility.Facility) error {
	return s.repo.Create(ctx, f)
}

func (s *FacilityService) Update(ctx context.Context, f *facility.Facility) error {
	return s.repo.Update(ctx, f)
}

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

func (s *FacilityService) GetByID(ctx context.Context, id []byte) (*facility.Facility, error) {
	return s.repo.GetByID(ctx, id)
}

func (s *FacilityService) List(ctx context.Context, filter, category, sort string, limit, offset int) ([]facility.Facility, int64, error) {
	return s.repo.List(ctx, filter, category, normalizeFacilitySort(sort), limit, offset)
}

func normalizeFacilitySort(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("category"),
		sortField("name"),
		sortField("type"),
		sortField("is_active"),
		sortField("created_at"),
		sortField("updated_at"),
	)
}
