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"
	m "gitlab.com/mbugroup/lti-api.git/internal/middleware"
	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("KandangGroup").Preload("Pic").Preload("ProjectFlockKandangs.ProjectFlock")

}

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
	}

	var scopeErr error

	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)
		db, scopeErr = m.ApplyLocationScope(c, db, "kandangs.location_id")
		if params.Search != "" {
			return db.Where("name ILIKE ?", "%"+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 scopeErr != nil {
		return nil, 0, scopeErr
	}
	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) {
	var scopeErr error

	kandang, err := s.Repository.GetByID(c.Context(), id, func(db *gorm.DB) *gorm.DB {
		db = s.withRelations(db)
		db, scopeErr = m.ApplyLocationScope(c, db, "kandangs.location_id")
		return db
	})
	if scopeErr != nil {
		return nil, scopeErr
	}
	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) ensureKandangGroupAccess(c *fiber.Ctx, groupID uint, expectedLocationID *uint) error {
	var kandangGroup entity.KandangGroup
	if err := s.Repository.DB().WithContext(c.Context()).
		Select("id", "location_id").
		First(&kandangGroup, groupID).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return fiber.NewError(fiber.StatusNotFound, "Kandang group not found")
		}
		return err
	}

	if err := m.EnsureLocationAccess(c, s.Repository.DB(), kandangGroup.LocationId); err != nil {
		return fiber.NewError(fiber.StatusNotFound, "Kandang group not found")
	}

	if expectedLocationID != nil && kandangGroup.LocationId != *expectedLocationID {
		return fiber.NewError(fiber.StatusBadRequest, "Kandang group location must match kandang location")
	}

	return 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 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 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: "KandangGroup", ID: &req.GroupId, Exists: s.Repository.KandangGroupExists},
		common.RelationCheck{Name: "Pic", ID: &req.PicId, Exists: s.Repository.PicExists},
	); err != nil {
		return nil, err
	}
	if err := s.ensureKandangGroupAccess(c, req.GroupId, &req.LocationId); 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")
	}

	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")
			}
		}

	}

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

	createBody := &entity.Kandang{
		Name:           req.Name,
		LocationId:     req.LocationId,
		KandangGroupId: req.GroupId,
		Capacity:       req.Capacity,
		Status:         status,
		PicId:          req.PicId,
		CreatedBy:      actorID,
	}

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

	if req.ProjectFlockId != nil {
		if err := s.Repository.UpsertProjectFlockKandang(c.Context(), *req.ProjectFlockId, createBody.Id); err != nil {
			s.Log.Errorf("Failed to link kandang to project_flock via pivot: %+v", err)
			return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to link kandang to project flock")
		}
	}
	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
	}
	if err := m.EnsureKandangAccess(c, s.Repository.DB(), id); err != nil {
		return nil, err
	}
	if req.LocationId != nil {
		if err := m.EnsureLocationAccess(c, s.Repository.DB(), *req.LocationId); 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: "KandangGroup", ID: req.GroupId, Exists: s.Repository.KandangGroupExists},
		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.GroupId != nil {
		targetLocationID := existing.LocationId
		if req.LocationId != nil {
			targetLocationID = *req.LocationId
		}
		if err := s.ensureKandangGroupAccess(c, *req.GroupId, &targetLocationID); err != nil {
			return nil, err
		}
		updateBody["kandang_group_id"] = *req.GroupId
	}

	if req.PicId != nil {
		updateBody["pic_id"] = *req.PicId
	}

	if req.Capacity != nil {
		updateBody["capacity"] = *req.Capacity
	}

	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
	}

	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))
		}

		// Kalau status jadi ACTIVE, pastikan tidak ada kandang aktif lain pada project flock tsb (hitung via pivot)
		if finalStatus == string(utils.KandangStatusActive) {
			if active, err := s.Repository.HasActiveKandangForProjectFlock(c.Context(), *req.ProjectFlockId, &id); 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")
			}
		}
	}

	if len(updateBody) > 0 {
		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
		}
	}

	if req.ProjectFlockId != nil {
		if err := s.Repository.UpsertProjectFlockKandang(c.Context(), *req.ProjectFlockId, id); err != nil {
			s.Log.Errorf("Failed to upsert pivot kandang-project_flock: %+v", err)
			return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to link kandang to project flock")
		}
	}

	return s.GetOne(c, id)
}

func (s kandangService) DeleteOne(c *fiber.Ctx, id uint) error {
	if err := m.EnsureKandangAccess(c, s.Repository.DB(), id); err != nil {
		return err
	}

	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
}
