package service

import (
	"context"

	helicopterusage "wucher/internal/domain/helicopter_usage"
)

type HelicopterUsageService struct {
	repo helicopterusage.Repository
}

func NewHelicopterUsageService(repo helicopterusage.Repository) *HelicopterUsageService {
	return &HelicopterUsageService{repo: repo}
}

func (s *HelicopterUsageService) Create(ctx context.Context, row *helicopterusage.HelicopterUsage) error {
	return s.repo.Create(ctx, row)
}

func (s *HelicopterUsageService) Update(ctx context.Context, row *helicopterusage.HelicopterUsage) error {
	return s.repo.Update(ctx, row)
}

func (s *HelicopterUsageService) ReviseManualTotals(ctx context.Context, helicopterID []byte, in helicopterusage.ManualSummaryInput, actor []byte) error {
	if len(helicopterID) != 16 {
		return nil
	}
	row, err := s.repo.GetByHelicopterID(ctx, helicopterID)
	if err != nil {
		return err
	}
	if row == nil {
		row = &helicopterusage.HelicopterUsage{HelicopterID: append([]byte(nil), helicopterID...), CreatedBy: actor}
	}
	row.ApplyManualSummary(in)
	row.UpdatedBy = actor
	if len(row.ID) == 0 {
		return s.repo.Create(ctx, row)
	}
	return s.repo.Update(ctx, row)
}

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

func (s *HelicopterUsageService) RefreshAll(ctx context.Context) error {
	if refresher, ok := s.repo.(interface {
		RefreshAll(context.Context) error
	}); ok {
		return refresher.RefreshAll(ctx)
	}
	return nil
}

func (s *HelicopterUsageService) GetByID(ctx context.Context, id []byte) (*helicopterusage.HelicopterUsage, error) {
	return s.repo.GetByID(ctx, id)
}

func (s *HelicopterUsageService) GetByHelicopterID(ctx context.Context, helicopterID []byte) (*helicopterusage.HelicopterUsage, error) {
	return s.repo.GetByHelicopterID(ctx, helicopterID)
}

func (s *HelicopterUsageService) FlightStatsByFlightID(ctx context.Context, flightID []byte) (helicopterusage.FlightDayStats, error) {
	return s.repo.FlightStatsByFlightID(ctx, flightID)
}

func (s *HelicopterUsageService) List(ctx context.Context, filter, sort string, limit, offset int) ([]helicopterusage.HelicopterUsage, int64, error) {
	return s.repo.List(ctx, filter, normalizeSortByRules(sort,
		sortField("helicopter_id"),
		sortField("total_landing"),
		sortField("total_airframe_hours"),
		sortField("total_airframe_cycles"),
		sortField("total_engine_1_hours"),
		sortField("total_engine_1_gpc_ng_n1"),
		sortField("total_engine_1_ptc_nf_n2"),
		sortField("total_engine_1_ccc"),
		sortField("total_engine_2_hours"),
		sortField("total_engine_2_gpc_ng_n1"),
		sortField("total_engine_2_ptc_nf_n2"),
		sortField("total_engine_2_ccc"),
		sortField("total_flight_report"),
		sortField("total_hook_release"),
		sortField("total_rotor_brake_cycle"),
		sortField("created_at"),
		sortField("updated_at"),
	), limit, offset)
}
