package service

import (
	"errors"
	"fmt"

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

type fcrService struct {
	Log        *logrus.Logger
	Validate   *validator.Validate
	Repository repository.FcrRepository
}

func NewFcrService(repo repository.FcrRepository, validate *validator.Validate) FcrService {
	return &fcrService{
		Log:        utils.Log,
		Validate:   validate,
		Repository: repo,
	}
}

func (s fcrService) withRelations(db *gorm.DB) *gorm.DB {
	return db.
		Preload("CreatedUser").
		Preload("Standards", func(db *gorm.DB) *gorm.DB {
			return db.Order("weight ASC")
		})
}

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

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

	fcrs, 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 fcrs: %+v", err)
		return nil, 0, err
	}
	return fcrs, total, nil
}

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

func (s *fcrService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.Fcr, 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 fcr name: %+v", err)
		return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check fcr name")
	} else if exists {
		return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Fcr with name %s already exists", req.Name))
	}

	createBody := &entity.Fcr{
		Name:      req.Name,
		CreatedBy: 1,
	}

	err := s.Repository.DB().WithContext(c.Context()).Transaction(func(tx *gorm.DB) error {
		repoTx := s.Repository.WithTx(tx)

		if err := repoTx.CreateOne(c.Context(), createBody, nil); err != nil {
			return err
		}

		if len(req.FcrStandards) == 0 {
			return nil
		}

		standards := make([]entity.FcrStandard, len(req.FcrStandards))
		for i, std := range req.FcrStandards {
			standards[i] = entity.FcrStandard{
				FcrID:     createBody.Id,
				Weight:    std.Weight,
				FcrNumber: std.FcrNumber,
				Mortality: std.Mortality,
			}
		}

		if err := s.Repository.SyncStandardsDiff(c.Context(), tx, createBody.Id, standards); err != nil {
			return err
		}

		return nil
	})

	if err != nil {
		s.Log.Errorf("Failed to create fcr: %+v", err)
		return nil, err
	}

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

func (s fcrService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.Fcr, 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 fcr name: %+v", err)
			return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check fcr name")
		} else if exists {
			return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Fcr with name %s already exists", *req.Name))
		}
		updateBody["name"] = *req.Name
	}

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

	err := s.Repository.DB().WithContext(c.Context()).Transaction(func(tx *gorm.DB) error {
		repoTx := s.Repository.WithTx(tx)

		if len(updateBody) > 0 {
			if err := repoTx.PatchOne(c.Context(), id, updateBody, nil); err != nil {
				return err
			}
		} else {
			if _, err := repoTx.GetByID(c.Context(), id, nil); err != nil {
				return err
			}
		}

		if req.FcrStandards != nil {
			standards := make([]entity.FcrStandard, len(req.FcrStandards))
			for i, std := range req.FcrStandards {
				standards[i] = entity.FcrStandard{
					FcrID:     id,
					Weight:    std.Weight,
					FcrNumber: std.FcrNumber,
					Mortality: std.Mortality,
				}
			}

			if err := s.Repository.SyncStandardsDiff(c.Context(), tx, id, standards); err != nil {
				return err
			}
		}

		return nil
	})

	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, fiber.NewError(fiber.StatusNotFound, "Fcr not found")
		}
		s.Log.Errorf("Failed to update fcr: %+v", err)
		return nil, err
	}

	return s.GetOne(c, id)
}

func (s fcrService) DeleteOne(c *fiber.Ctx, id uint) error {
	err := s.Repository.DB().WithContext(c.Context()).Transaction(func(tx *gorm.DB) error {
		repoTx := s.Repository.WithTx(tx)

		if err := s.Repository.SyncStandardsDiff(c.Context(), tx, id, nil); err != nil {
			return err
		}

		return repoTx.DeleteOne(c.Context(), id)
	})

	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return fiber.NewError(fiber.StatusNotFound, "Fcr not found")
		}
		s.Log.Errorf("Failed to delete fcr: %+v", err)
		return err
	}

	return nil
}
