package service

import (
	"errors"
	"fmt"
	"strings"

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

type kandangService struct {
	Log        *logrus.Logger
	Validate   *validator.Validate
	Repository repository.KandangRepository
}

func NewKandangService(repo repository.KandangRepository, validate *validator.Validate) KandangService {
	return &kandangService{
		Log:        utils.Log,
		Validate:   validate,
		Repository: repo,
	}
}

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

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

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

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

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

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

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

	var projectFlockID *uint
	if req.ProjectFlockId != nil {
		if exists, err := s.Repository.ProjectFlockExists(c.Context(), *req.ProjectFlockId); err != nil {
			s.Log.Errorf("Failed to check project flock existence: %+v", err)
			return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check project flock")
		} else if !exists {
			return nil, fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Project flock with id %d not found", *req.ProjectFlockId))
		}

		if status == string(utils.KandangStatusActive) {
			if active, err := s.Repository.HasActiveKandangForProjectFlock(c.Context(), *req.ProjectFlockId, nil); err != nil {
				s.Log.Errorf("Failed to check kandang activity for project flock %d: %+v", *req.ProjectFlockId, err)
				return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check active kandang for project flock")
			} else if active {
				return nil, fiber.NewError(fiber.StatusConflict, "Project flock already has an active kandang")
			}
		}

		idCopy := *req.ProjectFlockId
		projectFlockID = &idCopy
	}

	//TODO: created by dummy
	createBody := &entity.Kandang{
		Name:           req.Name,
		LocationId:     req.LocationId,
		Status:         status,
		PicId:          req.PicId,
		ProjectFlockId: projectFlockID,
		CreatedBy:      1,
	}

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

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

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

	existing, err := s.Repository.GetByID(c.Context(), id, nil)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, fiber.NewError(fiber.StatusNotFound, "Kandang not found")
	}
	if err != nil {
		s.Log.Errorf("Failed to fetch kandang %d before update: %+v", id, err)
		return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch kandang")
	}

	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 name: %+v", err)
			return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check kandang name")
		} else if exists {
			return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Kandang 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
	}

	finalStatus := strings.ToUpper(existing.Status)
	if req.Status != nil {
		status := strings.ToUpper(*req.Status)
		if !utils.IsValidKandangStatus(status) {
			return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid kandang status")
		}
		updateBody["status"] = status
		finalStatus = status
	}

	projectFlockIDToUse := existing.ProjectFlockId
	if req.ProjectFlockId != nil {
		if exists, err := s.Repository.ProjectFlockExists(c.Context(), *req.ProjectFlockId); err != nil {
			s.Log.Errorf("Failed to check project flock existence: %+v", err)
			return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check project flock")
		} else if !exists {
			return nil, fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Project flock with id %d not found", *req.ProjectFlockId))
		}
		idCopy := *req.ProjectFlockId
		projectFlockIDToUse = &idCopy
		updateBody["project_flock_id"] = idCopy
	}

	if projectFlockIDToUse != nil && finalStatus == string(utils.KandangStatusActive) {
		if active, err := s.Repository.HasActiveKandangForProjectFlock(c.Context(), *projectFlockIDToUse, &id); err != nil {
			s.Log.Errorf("Failed to check kandang activity for project flock %d: %+v", *projectFlockIDToUse, err)
			return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check active kandang for project flock")
		} else if active {
			return nil, fiber.NewError(fiber.StatusConflict, "Project flock already has an active kandang")
		}
	}

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

	return s.GetOne(c, id)
}

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