package service

import (
	"errors"
	"fmt"
	"strings"

	"github.com/go-playground/validator/v10"
	"github.com/gofiber/fiber/v2"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"

	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/kandang-groups/repositories"
	validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/kandang-groups/validations"
	"gitlab.com/mbugroup/lti-api.git/internal/utils"
)

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

type kandangGroupService struct {
	Log        *logrus.Logger
	Validate   *validator.Validate
	Repository repository.KandangGroupRepository
}

func NewKandangGroupService(repo repository.KandangGroupRepository, validate *validator.Validate) KandangGroupService {
	return &kandangGroupService{
		Log:        utils.Log,
		Validate:   validate,
		Repository: repo,
	}
}

func (s kandangGroupService) withRelations(db *gorm.DB) *gorm.DB {
	return db.
		Preload("CreatedUser").
		Preload("Location").
		Preload("Pic").
		Preload("Kandangs", func(tx *gorm.DB) *gorm.DB {
			return tx.Select("id", "name", "kandang_group_id").Order("name ASC")
		})
}

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

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

	kandangGroups, 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, "kandang_groups.location_id")
		if params.Search != "" {
			db = db.Where("kandang_groups.name ILIKE ?", "%"+params.Search+"%")
		}
		if params.LocationId != 0 {
			db = db.Where("kandang_groups.location_id = ?", params.LocationId)
		}
		if params.PicId != 0 {
			db = db.Where("kandang_groups.pic_id = ?", params.PicId)
		}
		return db.Order("kandang_groups.created_at DESC").Order("kandang_groups.updated_at DESC")
	})

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

	return kandangGroups, total, nil
}

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

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

	return kandangGroup, nil
}

func (s *kandangGroupService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.KandangGroup, error) {
	if err := s.Validate.Struct(req); err != nil {
		return nil, err
	}
	if err := m.EnsureLocationAccess(c, s.Repository.DB(), req.LocationId); err != nil {
		return nil, err
	}

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

	if err := common.EnsureRelations(c.Context(),
		common.RelationCheck{Name: "Location", ID: &req.LocationId, Exists: s.Repository.LocationExists},
		common.RelationCheck{Name: "Pic", ID: &req.PicId, Exists: s.Repository.PicExists},
	); err != nil {
		return nil, err
	}

	status := strings.ToUpper(strings.TrimSpace(req.Status))
	if status == "" {
		status = string(utils.KandangStatusNonActive)
	}
	if !utils.IsValidKandangStatus(status) {
		return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid kandang group status")
	}

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

	createBody := &entity.KandangGroup{
		Name:       req.Name,
		Status:     status,
		LocationId: req.LocationId,
		PicId:      req.PicId,
		CreatedBy:  actorID,
	}

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

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

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

	existing, err := s.GetOne(c, id)
	if err != nil {
		return nil, err
	}

	if req.LocationId != nil {
		if err := m.EnsureLocationAccess(c, s.Repository.DB(), *req.LocationId); 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 kandang group name: %+v", err)
			return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check kandang group name")
		} else if exists {
			return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Kandang group with name %s already exists", *req.Name))
		}
		updateBody["name"] = *req.Name
	}

	if err := common.EnsureRelations(c.Context(),
		common.RelationCheck{Name: "Location", ID: req.LocationId, Exists: s.Repository.LocationExists},
		common.RelationCheck{Name: "Pic", ID: req.PicId, Exists: s.Repository.PicExists},
	); err != nil {
		return nil, err
	}

	if req.LocationId != nil {
		updateBody["location_id"] = *req.LocationId
	}
	if req.PicId != nil {
		updateBody["pic_id"] = *req.PicId
	}
	if req.Status != nil {
		status := strings.ToUpper(strings.TrimSpace(*req.Status))
		if !utils.IsValidKandangStatus(status) {
			return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid kandang group status")
		}
		updateBody["status"] = status
	}

	if len(updateBody) == 0 {
		return existing, nil
	}

	if err := s.Repository.PatchOne(c.Context(), id, updateBody, nil); err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, fiber.NewError(fiber.StatusNotFound, "Kandang group not found")
		}
		s.Log.Errorf("Failed to update kandang group: %+v", err)
		return nil, err
	}

	return s.GetOne(c, id)
}

func (s kandangGroupService) DeleteOne(c *fiber.Ctx, id uint) error {
	kandangGroup, err := s.GetOne(c, id)
	if err != nil {
		return err
	}

	hasDailyChecklistRelation, err := s.Repository.HasDailyChecklistRelation(c.Context(), id)
	if err != nil {
		s.Log.Errorf("Failed to check daily checklist relation for kandang group %d: %+v", id, err)
		return fiber.NewError(fiber.StatusInternalServerError, "Failed to check kandang group relation")
	}
	if hasDailyChecklistRelation {
		return fiber.NewError(fiber.StatusConflict, "Kandang group tidak boleh dihapus karena masih memiliki relasi daily checklist")
	}

	if len(kandangGroup.Kandangs) > 0 {
		return fiber.NewError(fiber.StatusConflict, "Kandang group tidak boleh dihapus karena masih memiliki relasi kandang")
	}

	if err := s.Repository.DeleteOne(c.Context(), id); err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return fiber.NewError(fiber.StatusNotFound, "Kandang group not found")
		}
		s.Log.Errorf("Failed to delete kandang group: %+v", err)
		return err
	}

	return nil
}
