package service

import (
	"errors"
	"time"

	entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
	repository "gitlab.com/mbugroup/lti-api.git/internal/modules/master/config-checklists/repositories"
	validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/config-checklists/validations"
	"gitlab.com/mbugroup/lti-api.git/internal/utils"

	"github.com/go-playground/validator/v10"
	"github.com/gofiber/fiber/v2"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

type ConfigChecklistService interface {
	GetAll(ctx *fiber.Ctx, params *validation.Query) ([]entity.ConfigChecklist, int64, error)
	GetOne(ctx *fiber.Ctx, id uint) (*entity.ConfigChecklist, error)
	CreateOne(ctx *fiber.Ctx, req *validation.Create) (*entity.ConfigChecklist, error)
	UpdateOne(ctx *fiber.Ctx, req *validation.Update, id uint) (*entity.ConfigChecklist, error)
	DeleteOne(ctx *fiber.Ctx, id uint) error
}

type configChecklistService struct {
	Log        *logrus.Logger
	Validate   *validator.Validate
	Repository repository.ConfigChecklistRepository
}

func NewConfigChecklistService(repo repository.ConfigChecklistRepository, validate *validator.Validate) ConfigChecklistService {
	return &configChecklistService{
		Log:        utils.Log,
		Validate:   validate,
		Repository: repo,
	}
}

func (s configChecklistService) withRelations(db *gorm.DB) *gorm.DB {
	return db
}

func (s configChecklistService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.ConfigChecklist, int64, error) {
	if err := s.Validate.Struct(params); err != nil {
		return nil, 0, err
	}

	offset := (params.Page - 1) * params.Limit

	configChecklists, total, err := s.Repository.GetAll(c.Context(), offset, params.Limit, func(db *gorm.DB) *gorm.DB {
		db = s.withRelations(db)
		return db.Order("date DESC").Order("created_at DESC")
	})

	if err != nil {
		s.Log.Errorf("Failed to get configChecklists: %+v", err)
		return nil, 0, err
	}
	return configChecklists, total, nil
}

func (s configChecklistService) GetOne(c *fiber.Ctx, id uint) (*entity.ConfigChecklist, error) {
	configChecklist, err := s.Repository.GetByID(c.Context(), id, s.withRelations)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, fiber.NewError(fiber.StatusNotFound, "ConfigChecklist not found")
	}
	if err != nil {
		s.Log.Errorf("Failed get configChecklist by id: %+v", err)
		return nil, err
	}
	return configChecklist, nil
}

func (s *configChecklistService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.ConfigChecklist, error) {
	if err := s.Validate.Struct(req); err != nil {
		return nil, err
	}
	if req.PercentageThresholdBad > req.PercentageThresholdEnough {
		return nil, fiber.NewError(fiber.StatusBadRequest, "percentage_threshold_bad cannot be greater than percentage_threshold_enough")
	}

	date, err := time.Parse("2006-01-02", req.Date)
	if err != nil {
		return nil, fiber.NewError(fiber.StatusBadRequest, "invalid date format, use YYYY-MM-DD")
	}

	createBody := &entity.ConfigChecklist{
		Date:                      date,
		PercentageThresholdBad:    req.PercentageThresholdBad,
		PercentageThresholdEnough: req.PercentageThresholdEnough,
	}

	if err := s.Repository.CreateOne(c.Context(), createBody, nil); err != nil {
		s.Log.Errorf("Failed to create configChecklist: %+v", err)
		return nil, err
	}

	return s.GetOne(c, createBody.Id)
}

func (s configChecklistService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.ConfigChecklist, error) {
	if err := s.Validate.Struct(req); err != nil {
		return nil, err
	}
	if req.PercentageThresholdBad != nil && req.PercentageThresholdEnough != nil {
		if *req.PercentageThresholdBad > *req.PercentageThresholdEnough {
			return nil, fiber.NewError(fiber.StatusBadRequest, "percentage_threshold_bad cannot be greater than percentage_threshold_enough")
		}
	}

	updateBody := make(map[string]any)

	if req.Date != nil {
		date, err := time.Parse("2006-01-02", *req.Date)
		if err != nil {
			return nil, fiber.NewError(fiber.StatusBadRequest, "invalid date format, use YYYY-MM-DD")
		}
		updateBody["date"] = date
	}

	if req.PercentageThresholdBad != nil {
		updateBody["percentage_threshold_bad"] = *req.PercentageThresholdBad
	}

	if req.PercentageThresholdEnough != nil {
		updateBody["percentage_threshold_enough"] = *req.PercentageThresholdEnough
	}

	if len(updateBody) == 0 {
		return s.GetOne(c, id)
	}

	if err := s.Repository.PatchOne(c.Context(), id, updateBody, nil); err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, fiber.NewError(fiber.StatusNotFound, "ConfigChecklist not found")
		}
		s.Log.Errorf("Failed to update configChecklist: %+v", err)
		return nil, err
	}

	return s.GetOne(c, id)
}

func (s configChecklistService) DeleteOne(c *fiber.Ctx, id uint) error {
	if err := s.Repository.DeleteOne(c.Context(), id); err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return fiber.NewError(fiber.StatusNotFound, "ConfigChecklist not found")
		}
		s.Log.Errorf("Failed to delete configChecklist: %+v", err)
		return err
	}
	return nil
}
