package service

import (
	"context"

	"gorm.io/gorm"

	fleetstatus "wucher/internal/domain/fleet_status"
	"wucher/internal/domain/helicopter"
	"wucher/internal/shared/pkg/sortkey"
)

type HelicopterService struct {
	repo   helicopter.Repository
	txRepo helicopterTxRepository
}

func NewHelicopterService(repo helicopter.Repository) *HelicopterService {
	svc := &HelicopterService{repo: repo}
	if txRepo, ok := repo.(helicopterTxRepository); ok {
		svc.txRepo = txRepo
	}
	return svc
}

type helicopterTxRepository interface {
	helicopter.Repository
	Transaction(ctx context.Context, fn func(tx *gorm.DB) error) error
	CreateWithDB(ctx context.Context, db *gorm.DB, h *helicopter.Helicopter) error
}

func (s *HelicopterService) Create(ctx context.Context, h *helicopter.Helicopter) error {
	if h != nil {
		h.EnforceAOGInactive()
	}
	if s.txRepo == nil {
		if err := s.repo.Create(ctx, h); err != nil {
			return err
		}
		return nil
	}
	return s.txRepo.Transaction(ctx, func(tx *gorm.DB) error {
		if err := s.txRepo.CreateWithDB(ctx, tx, h); err != nil {
			return err
		}
		if h != nil && len(h.ID) == 16 {
			return tx.WithContext(ctx).Create(&fleetstatus.FleetStatus{HelicopterID: append([]byte(nil), h.ID...)}).Error
		}
		return nil
	})
}

func (s *HelicopterService) Update(ctx context.Context, h *helicopter.Helicopter) error {
	if h != nil {
		h.EnforceAOGInactive()
	}
	return s.repo.Update(ctx, h)
}

func (s *HelicopterService) ExistsByIdentifier(ctx context.Context, identifier string, excludeID []byte) (bool, error) {
	return s.repo.ExistsByIdentifier(ctx, identifier, excludeID)
}

func (s *HelicopterService) ApplySortKeyPatch(h *helicopter.Helicopter, patch helicopter.SortKeyPatch) {
	if h == nil || !patch.Set {
		return
	}
	if patch.Value == nil {
		h.SortKey = nil
		return
	}
	v := *patch.Value
	h.SortKey = &v
}

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

func (s *HelicopterService) GetByID(ctx context.Context, id []byte) (*helicopter.Helicopter, error) {
	return s.repo.GetByID(ctx, id)
}

func (s *HelicopterService) List(ctx context.Context, filter string, statuses []string, sort string, limit, offset int, groundedIDs [][]byte) ([]helicopter.Helicopter, int64, error) {
	return s.repo.List(ctx, filter, statuses, normalizeHelicopterSort(sort), limit, offset, groundedIDs)
}

func (s *HelicopterService) NextReportNumber(ctx context.Context, id []byte) (string, int, error) {
	return s.repo.NextReportNumber(ctx, id)
}

func (s *HelicopterService) IsInUse(ctx context.Context, id []byte) (bool, error) {
	return s.repo.IsInUse(ctx, id)
}

func (s *HelicopterService) InUseByAircraftIDs(ctx context.Context, ids [][]byte) (map[string]bool, error) {
	return s.repo.InUseByAircraftIDs(ctx, ids)
}

func (s *HelicopterService) ActiveFlightIDByAircraftIDs(ctx context.Context, ids [][]byte) (map[string][]byte, error) {
	return s.repo.ActiveFlightIDByAircraftIDs(ctx, ids)
}

func normalizeHelicopterSort(sort string) string {
	return normalizeSortByRules(sort,
		sortField("designation"),
		sortExpr(
			joinSortClauses(sortkey.ActivePositiveSortClauses("", "is_active", "sortkey", "designation", false)),
			joinSortClauses(sortkey.ActivePositiveSortClauses("", "is_active", "sortkey", "designation", true)),
			"sortkey",
		),
	)
}
