package service

import (
	"errors"
	"fmt"
	"strings"

	entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
	repository "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/repositories"
	validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/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 FlockService interface {
	GetAll(ctx *fiber.Ctx, params *validation.Query) ([]entity.Flock, int64, error)
	GetOne(ctx *fiber.Ctx, id uint) (*entity.Flock, error)
	CreateOne(ctx *fiber.Ctx, req *validation.Create) (*entity.Flock, error)
	UpdateOne(ctx *fiber.Ctx, req *validation.Update, id uint) (*entity.Flock, error)
	DeleteOne(ctx *fiber.Ctx, id uint) error
}

type flockService struct {
	Log        *logrus.Logger
	Validate   *validator.Validate
	Repository repository.FlockRepository
}

func NewFlockService(repo repository.FlockRepository, validate *validator.Validate) FlockService {
	return &flockService{
		Log:        utils.Log,
		Validate:   validate,
		Repository: repo,
	}
}

func (s flockService) withRelations(db *gorm.DB) *gorm.DB {
	return db.Preload("CreatedUser")
}

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

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

	flocks, total, err := s.Repository.GetAll(c.Context(), offset, params.Limit, func(db *gorm.DB) *gorm.DB {
		db = s.withRelations(db)
		if params.Search != "" {
			return db.Where("name ILIKE ?", "%"+params.Search+"%")
		}
		return db.Order("created_at DESC").Order("updated_at DESC")
	})

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

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

func (s *flockService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.Flock, error) {
	if err := s.Validate.Struct(req); err != nil {
		return nil, err
	}

	name := strings.TrimSpace(req.Name)
	if name == "" {
		return nil, fiber.NewError(fiber.StatusBadRequest, "Name is required")
	}

	exists, err := s.Repository.NameExists(c.Context(), name, nil)
	if err != nil {
		s.Log.Errorf("Failed to check flock name: %+v", err)
		return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check flock name")
	}
	if exists {
		return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Flock with name %s already exists", name))
	}

	createBody := &entity.Flock{
		Name:      name,
		CreatedBy: 1,
	}

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

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

func (s flockService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.Flock, error) {
	if err := s.Validate.Struct(req); err != nil {
		return nil, err
	}

	updateBody := make(map[string]any)

	if req.Name != nil {
		name := strings.TrimSpace(*req.Name)
		if name == "" {
			return nil, fiber.NewError(fiber.StatusBadRequest, "Name cannot be empty")
		}

		exists, err := s.Repository.NameExists(c.Context(), name, &id)
		if err != nil {
			s.Log.Errorf("Failed to check flock name: %+v", err)
			return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check flock name")
		}
		if exists {
			return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Flock with name %s already exists", name))
		}
		updateBody["name"] = name
	}

	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, "Flock not found")
		}
		s.Log.Errorf("Failed to update flock: %+v", err)
		return nil, err
	}

	return s.GetOne(c, id)
}

func (s flockService) 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, "Flock not found")
		}
		s.Log.Errorf("Failed to delete flock: %+v", err)
		return err
	}
	return nil
}
