package service

import (
	"context"
	"strings"

	flightinspectionfilechecklist "wucher/internal/domain/flight_inspection_file_checklist"
)

type FlightInspectionFileChecklistService struct {
	repo flightinspectionfilechecklist.Repository
}

func NewFlightInspectionFileChecklistService(repo flightinspectionfilechecklist.Repository) *FlightInspectionFileChecklistService {
	return &FlightInspectionFileChecklistService{repo: repo}
}

func (s *FlightInspectionFileChecklistService) Create(ctx context.Context, row *flightinspectionfilechecklist.FlightInspectionFileChecklist) error {
	return s.repo.Create(ctx, row)
}

func (s *FlightInspectionFileChecklistService) Update(ctx context.Context, row *flightinspectionfilechecklist.FlightInspectionFileChecklist) error {
	return s.repo.Update(ctx, row)
}

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

func (s *FlightInspectionFileChecklistService) GetByID(ctx context.Context, id []byte) (*flightinspectionfilechecklist.FlightInspectionFileChecklist, error) {
	return s.repo.GetByID(ctx, id)
}

func (s *FlightInspectionFileChecklistService) List(ctx context.Context, filter string, sort string, limit, offset int) ([]flightinspectionfilechecklist.FlightInspectionFileChecklist, int64, error) {
	return s.repo.List(ctx, filter, normalizeFlightInspectionFileChecklistSort(sort), limit, offset)
}

func (s *FlightInspectionFileChecklistService) ListByInspectionID(ctx context.Context, inspectionID []byte) ([]flightinspectionfilechecklist.FlightInspectionFileChecklist, error) {
	return s.repo.ListByInspectionID(ctx, inspectionID)
}

func (s *FlightInspectionFileChecklistService) FlightInspectionExists(ctx context.Context, inspectionID []byte) (bool, error) {
	return s.repo.FlightInspectionExists(ctx, inspectionID)
}

func (s *FlightInspectionFileChecklistService) HelicopterFileExists(ctx context.Context, helicopterFileID []byte) (bool, error) {
	return s.repo.HelicopterFileExists(ctx, helicopterFileID)
}

func normalizeFlightInspectionFileChecklistSort(sort string) string {
	if normalized := normalizeSortByRules(strings.TrimSpace(sort),
		sortExpr("is_done ASC, created_at ASC", "is_done DESC, created_at DESC", "is_done"),
		sortField("created_at"),
		sortField("updated_at"),
	); normalized != "" {
		return normalized
	}
	return "created_at DESC"
}
