package service

import (
	"context"

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

type HealthInsuranceCompaniesService struct {
	repo health_insurance_companies.Repository
}

func NewHealthInsuranceCompaniesService(repo health_insurance_companies.Repository) *HealthInsuranceCompaniesService {
	return &HealthInsuranceCompaniesService{repo: repo}
}

func (s *HealthInsuranceCompaniesService) Create(ctx context.Context, row *health_insurance_companies.HealthInsuranceCompany) error {
	return s.repo.Create(ctx, row)
}

func (s *HealthInsuranceCompaniesService) Update(ctx context.Context, row *health_insurance_companies.HealthInsuranceCompany) error {
	return s.repo.Update(ctx, row)
}

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

func (s *HealthInsuranceCompaniesService) GetByID(ctx context.Context, id []byte) (*health_insurance_companies.HealthInsuranceCompany, error) {
	return s.repo.GetByID(ctx, id)
}

func (s *HealthInsuranceCompaniesService) List(ctx context.Context, filter, sort string, limit, offset int) ([]health_insurance_companies.HealthInsuranceCompany, int64, error) {
	return s.repo.List(ctx, filter, normalizeHealthInsuranceCompaniesSort(sort), limit, offset)
}

func (s *HealthInsuranceCompaniesService) ResolveStateDetails(ctx context.Context, stateNames []string) (map[string]health_insurance_companies.StateDetail, error) {
	return s.repo.ResolveStateDetails(ctx, stateNames)
}

func (s *HealthInsuranceCompaniesService) ResolveLandDetails(ctx context.Context, landIDs []string) (map[string]health_insurance_companies.LandDetail, error) {
	return s.repo.ResolveLandDetails(ctx, landIDs)
}

func normalizeHealthInsuranceCompaniesSort(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("state"),
		sortField("address"),
		sortField("mobile_number"),
		sortField("email"),
		sortField("note"),
		sortField("is_active"),
		sortField("created_at"),
		sortField("updated_at"),
	)
}
