package service

import (
	"context"

	"wucher/internal/domain/land"
	"wucher/internal/shared/pkg/sortkey"
	"wucher/internal/transport/http/dto"
)

type LandService struct {
	repo land.Repository
}

func NewLandService(repo land.Repository) *LandService {
	return &LandService{repo: repo}
}

func (s *LandService) Create(ctx context.Context, row *land.Land) error {
	return s.repo.Create(ctx, row)
}

func (s *LandService) Update(ctx context.Context, row *land.Land) error {
	return s.repo.Update(ctx, row)
}

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

func (s *LandService) GetByID(ctx context.Context, id []byte) (*land.Land, error) {
	return s.repo.GetByID(ctx, id)
}

func (s *LandService) List(ctx context.Context, filter, sort string, limit, offset int) ([]land.Land, int64, error) {
	return s.repo.List(ctx, filter, normalizeLandSort(sort), limit, offset)
}

func (s *LandService) GetByIDView(ctx context.Context, id []byte) (*dto.LandView, error) {
	if repo, ok := s.repo.(interface {
		GetByIDView(context.Context, []byte) (*dto.LandView, error)
	}); ok {
		return repo.GetByIDView(ctx, id)
	}
	row, err := s.repo.GetByID(ctx, id)
	if err != nil || row == nil {
		return nil, err
	}
	return &dto.LandView{Row: *row}, nil
}

func (s *LandService) ListView(ctx context.Context, filter, sort string, limit, offset int) ([]dto.LandView, int64, error) {
	if repo, ok := s.repo.(interface {
		ListView(context.Context, string, string, int, int) ([]dto.LandView, int64, error)
	}); ok {
		return repo.ListView(ctx, filter, normalizeLandSort(sort), limit, offset)
	}
	rows, total, err := s.repo.List(ctx, filter, normalizeLandSort(sort), limit, offset)
	if err != nil {
		return nil, 0, err
	}
	views := make([]dto.LandView, 0, len(rows))
	for i := range rows {
		views = append(views, dto.LandView{Row: rows[i]})
	}
	return views, total, nil
}

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