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

type productCategoryService struct {
	Log        *logrus.Logger
	Validate   *validator.Validate
	Repository repository.ProductCategoryRepository
}

func NewProductCategoryService(repo repository.ProductCategoryRepository, validate *validator.Validate) ProductCategoryService {
	return &productCategoryService{
		Log:        utils.Log,
		Validate:   validate,
		Repository: repo,
	}
}

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

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

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

	productCategories, total, err := s.Repository.GetAll(c.Context(), offset, params.Limit, func(db *gorm.DB) *gorm.DB {
		db = s.withRelations(db)
		if params.Search != "" {
			terms := splitSearchTerms(params.Search)
			if len(terms) == 0 {
				return db
			}
			if len(terms) == 1 {
				return db.Where("name ILIKE ?", "%"+terms[0]+"%")
			}
			for i, term := range terms {
				like := "%" + term + "%"
				if i == 0 {
					db = db.Where("name ILIKE ?", like)
				} else {
					db = db.Or("name ILIKE ?", like)
				}
			}
			return db
		}
		return db.Order("created_at DESC").Order("updated_at DESC")
	})

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

func splitSearchTerms(raw string) []string {
	parts := strings.FieldsFunc(raw, func(r rune) bool {
		return r == ',' || r == ';' || r == '|'
	})
	terms := make([]string, 0, len(parts))
	for _, part := range parts {
		trimmed := strings.TrimSpace(part)
		if trimmed != "" {
			terms = append(terms, trimmed)
		}
	}
	return terms
}

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

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

	ctx := c.Context()
	name := strings.TrimSpace(req.Name)
	code := strings.ToUpper(strings.TrimSpace(req.Code))

	if exists, err := s.Repository.NameExists(ctx, name, nil); err != nil {
		s.Log.Errorf("Failed to check product category name: %+v", err)
		return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check product category name")
	} else if exists {
		return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Product category with name %s already exists", name))
	}

	if exists, err := s.Repository.CodeExists(ctx, code, nil); err != nil {
		s.Log.Errorf("Failed to check product category code: %+v", err)
		return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check product category code")
	} else if exists {
		return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Product category with code %s already exists", code))
	}

	createBody := &entity.ProductCategory{
		Name:      name,
		Code:      code,
		CreatedBy: 1,
	}

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

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

func (s productCategoryService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.ProductCategory, 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")
		}
		if exists, err := s.Repository.NameExists(c.Context(), name, &id); err != nil {
			s.Log.Errorf("Failed to check product category name: %+v", err)
			return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check product category name")
		} else if exists {
			return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Product category with name %s already exists", name))
		}
		updateBody["name"] = name
	}

	if req.Code != nil {
		code := strings.ToUpper(strings.TrimSpace(*req.Code))
		if code == "" {
			return nil, fiber.NewError(fiber.StatusBadRequest, "Code cannot be empty")
		}
		if exists, err := s.Repository.CodeExists(c.Context(), code, &id); err != nil {
			s.Log.Errorf("Failed to check product category code: %+v", err)
			return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check product category code")
		} else if exists {
			return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Product category with code %s already exists", code))
		}
		updateBody["code"] = code
	}

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

	return s.GetOne(c, id)
}

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