package service

import (
	"context"

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

type OpcService struct {
	repo opc.Repository
}

func NewOpcService(repo opc.Repository) *OpcService {
	return &OpcService{repo: repo}
}

func (s *OpcService) Create(ctx context.Context, o *opc.Opc) error {
	return s.repo.Create(ctx, o)
}

func (s *OpcService) Update(ctx context.Context, o *opc.Opc) error {
	return s.repo.Update(ctx, o)
}

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

func (s *OpcService) GetByID(ctx context.Context, id []byte) (*opc.Opc, error) {
	return s.repo.GetByID(ctx, id)
}

func (s *OpcService) List(ctx context.Context, filter, sort string, limit, offset int) ([]opc.Opc, int64, error) {
	return s.repo.List(ctx, filter, normalizeOpcSort(sort), limit, offset)
}

func normalizeOpcSort(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", "title"),
		sortField("note"),
		sortField("is_active"),
		sortField("created_at"),
		sortField("updated_at"),
	)
}
