package service

import (
	"errors"
	"fmt"

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

type areaService struct {
	Log        *logrus.Logger
	Validate   *validator.Validate
	Repository repository.AreaRepository
}

func NewAreaService(repo repository.AreaRepository, validate *validator.Validate) AreaService {
	return &areaService{
		Log:        utils.Log,
		Validate:   validate,
		Repository: repo,
	}
}

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

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

	var scopeErr error

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

	areas, total, err := s.Repository.GetAll(c.Context(), offset, params.Limit, func(db *gorm.DB) *gorm.DB {
		db = s.withRelations(db)
		db, scopeErr = m.ApplyAreaScope(c, db, "id")
		if params.Search != "" {
			db = db.Where("name ILIKE ?", "%"+params.Search+"%")
		}
		return db.Order("name ASC").Order("id ASC")
	})

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

func (s areaService) GetOne(c *fiber.Ctx, id uint) (*entity.Area, error) {
	var scopeErr error

	area, err := s.Repository.GetByID(c.Context(), id, func(db *gorm.DB) *gorm.DB {
		db = s.withRelations(db)
		db, scopeErr = m.ApplyAreaScope(c, db, "id")
		return db
	})
	if scopeErr != nil {
		return nil, scopeErr
	}
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, fiber.NewError(fiber.StatusNotFound, "Area not found")
	}
	if err != nil {
		s.Log.Errorf("Failed get area by id: %+v", err)
		return nil, err
	}
	return area, nil
}

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

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

	actorID, err := m.ActorIDFromContext(c)
	if err != nil {
		return nil, err
	}

	createBody := &entity.Area{
		Name:      req.Name,
		CreatedBy: actorID,
	}

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

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

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

	updateBody := make(map[string]any)

	if req.Name != nil {
		if exists, err := s.Repository.NameExists(c.Context(), *req.Name, &id); err != nil {
			s.Log.Errorf("Failed to check area name: %+v", err)
			return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check area name")
		} else if exists {
			return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Area with name %s already exists", *req.Name))
		}
		updateBody["name"] = *req.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, "Area not found")
		}
		s.Log.Errorf("Failed to update area: %+v", err)
		return nil, err
	}

	return s.GetOne(c, id)
}

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