package service

import (
	"errors"
	"fmt"

	"github.com/go-playground/validator/v10"
	"github.com/gofiber/fiber/v2"
	"github.com/sirupsen/logrus"
	common "gitlab.com/mbugroup/lti-api.git/internal/common/service"
	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/locations/repositories"
	validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/locations/validations"
	"gitlab.com/mbugroup/lti-api.git/internal/utils"
	"gorm.io/gorm"
)

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

type locationService struct {
	Log        *logrus.Logger
	Validate   *validator.Validate
	Repository repository.LocationRepository
}

func NewLocationService(repo repository.LocationRepository, validate *validator.Validate) LocationService {
	return &locationService{
		Log:        utils.Log,
		Validate:   validate,
		Repository: repo,
	}
}

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

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

	var scopeErr error

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

	locations, total, err := s.Repository.GetAll(c.Context(), offset, params.Limit, func(db *gorm.DB) *gorm.DB {
		db = s.withRelations(db)
		db, scopeErr = m.ApplyLocationScope(c, db, "locations.id")
		if params.Search != "" {
			db = db.Where("name ILIKE ?", "%"+params.Search+"%")
		}
		if params.AreaId != 0 {
			db = db.Where("area_id = ?", params.AreaId)
		}
		if params.HasLaying {
			db = db.Where(`
				EXISTS (
					SELECT 1
					FROM project_flocks pf
					WHERE pf.location_id = locations.id
						AND pf.category = ?
						AND pf.deleted_at IS NULL
				)
			`, utils.ProjectFlockCategoryLaying)
		}
		return db.Order("locations.name ASC").Order("locations.id ASC")
	})

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

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

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

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

	if err := common.EnsureRelations(c.Context(),
		common.RelationCheck{Name: "Area", ID: &req.AreaId, Exists: s.Repository.AreaExists},
	); err != nil {
		return nil, err
	}

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

	createBody := &entity.Location{
		Name:      req.Name,
		Address:   req.Address,
		AreaId:    req.AreaId,
		CreatedBy: actorID,
	}

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

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

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

	if req.Address != nil {
		updateBody["address"] = *req.Address
	}

	if err := common.EnsureRelations(c.Context(), common.RelationCheck{Name: "Area", ID: req.AreaId, Exists: s.Repository.AreaExists}); err != nil {
		return nil, err
	}

	if req.AreaId != nil {
		updateBody["area_id"] = *req.AreaId
	}

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

	return s.GetOne(c, id)
}

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