package service

import (
	"errors"
	"strings"

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

type employeesService struct {
	Log        *logrus.Logger
	Validate   *validator.Validate
	Repository repository.EmployeesRepository
}

func NewEmployeesService(repo repository.EmployeesRepository, validate *validator.Validate) EmployeesService {
	return &employeesService{
		Log:        utils.Log,
		Validate:   validate,
		Repository: repo,
	}
}

func (s employeesService) withRelations(db *gorm.DB) *gorm.DB {
	return db.
		Preload("EmployeeKandangs.Kandang").
		Where("employees.deleted_at IS NULL")
}

func (s employeesService) ensureEmployeeAccess(c *fiber.Ctx, employeeID uint) error {
	if employeeID == 0 {
		return fiber.NewError(fiber.StatusBadRequest, "Invalid employee id")
	}

	db := s.Repository.DB().WithContext(c.Context()).
		Table("employees e").
		Joins("JOIN employee_kandangs ek ON ek.employee_id = e.id").
		Joins("JOIN kandang_groups k ON k.id = ek.kandang_id").
		Joins("JOIN locations loc ON loc.id = k.location_id").
		Joins("JOIN areas a ON a.id = loc.area_id").
		Where("e.id = ?", employeeID).
		Where("e.deleted_at IS NULL")

	scopedDB, err := m.ApplyLocationAreaScope(c, db, "loc.id", "a.id")
	if err != nil {
		return err
	}

	var count int64
	if err := scopedDB.Count(&count).Error; err != nil {
		return err
	}
	if count == 0 {
		return fiber.NewError(fiber.StatusNotFound, "Employees not found")
	}
	return nil
}

func (s employeesService) ensureKandangIDsAccess(c *fiber.Ctx, kandangIDs []uint) error {
	if len(kandangIDs) == 0 {
		return fiber.NewError(fiber.StatusBadRequest, "kandang_ids must contain at least one valid id")
	}

	db := s.Repository.DB().WithContext(c.Context()).
		Table("kandang_groups k").
		Joins("JOIN locations loc ON loc.id = k.location_id").
		Joins("JOIN areas a ON a.id = loc.area_id").
		Where("k.id IN ?", kandangIDs)

	scopedDB, err := m.ApplyLocationAreaScope(c, db, "loc.id", "a.id")
	if err != nil {
		return err
	}

	var count int64
	if err := scopedDB.Count(&count).Error; err != nil {
		return err
	}
	if count != int64(len(kandangIDs)) {
		return fiber.NewError(fiber.StatusNotFound, "Kandang not found")
	}
	return nil
}

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

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

	employeess, total, err := s.Repository.GetAll(c.Context(), offset, params.Limit, func(db *gorm.DB) *gorm.DB {
		db = s.withRelations(db)
		db = db.Joins("JOIN employee_kandangs ek ON ek.employee_id = employees.id").
			Joins("JOIN kandang_groups k ON k.id = ek.kandang_id").
			Joins("JOIN locations loc ON loc.id = k.location_id").
			Joins("JOIN areas a ON a.id = loc.area_id")
		var scopeErr error
		db, scopeErr = m.ApplyLocationAreaScope(c, db, "loc.id", "a.id")
		if scopeErr != nil {
			return db.Where("1 = 0")
		}
		if params.Search != "" {
			db = db.Where("employees.name ILIKE ?", "%"+params.Search+"%")
		}
		if params.KandangId != nil {
			db = db.Where("ek.kandang_id = ?", *params.KandangId)
		}
		if params.IsActive != nil {
			db = db.Where("employees.is_active = ?", *params.IsActive)
		}
		return db.
			Select("employees.id, employees.name, employees.is_active, employees.created_at, employees.updated_at").
			Group("employees.id, employees.name, employees.is_active, employees.created_at, employees.updated_at").
			Order("employees.created_at DESC").
			Order("employees.updated_at DESC")
	})

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

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

func (s *employeesService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.Employees, error) {
	if err := s.Validate.Struct(req); err != nil {
		return nil, err
	}

	name := strings.TrimSpace(req.Name)
	if name == "" {
		return nil, fiber.NewError(fiber.StatusBadRequest, "name cannot be empty")
	}

	kandangIDs := normalizeKandangIDs(req.KandangIDs)
	if len(kandangIDs) == 0 {
		return nil, fiber.NewError(fiber.StatusBadRequest, "kandang_ids must contain at least one valid id")
	}
	if err := s.ensureKandangIDsAccess(c, kandangIDs); err != nil {
		return nil, err
	}

	if _, err := s.Repository.First(c.Context(), func(db *gorm.DB) *gorm.DB {
		return db.Where("LOWER(name) = ?", strings.ToLower(name))
	}); err == nil {
		return nil, fiber.NewError(fiber.StatusBadRequest, "employee already exists")
	} else if !errors.Is(err, gorm.ErrRecordNotFound) {
		s.Log.Errorf("Failed checking employee uniqueness: %+v", err)
		return nil, err
	}

	createBody := &entity.Employees{
		Name:     name,
		IsActive: req.IsActive,
	}

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

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

		relations := make([]entity.EmployeeKandang, 0, len(kandangIDs))
		for _, kandangID := range kandangIDs {
			relations = append(relations, entity.EmployeeKandang{
				EmployeeId: createBody.Id,
				KandangId:  kandangID,
			})
		}

		if len(relations) > 0 {
			if err := tx.WithContext(c.Context()).Create(&relations).Error; err != nil {
				return err
			}
		}

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

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

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

	updateBody := make(map[string]any)
	var (
		kandangIDs        []uint
		needKandangUpdate bool
	)

	if req.Name != nil {
		trimmed := strings.TrimSpace(*req.Name)
		if trimmed == "" {
			return nil, fiber.NewError(fiber.StatusBadRequest, "name cannot be empty")
		}

		if _, err := s.Repository.First(c.Context(), func(db *gorm.DB) *gorm.DB {
			return db.Where("LOWER(name) = ? AND id <> ?", strings.ToLower(trimmed), id)
		}); err == nil {
			return nil, fiber.NewError(fiber.StatusBadRequest, "employee already exists")
		} else if !errors.Is(err, gorm.ErrRecordNotFound) {
			s.Log.Errorf("Failed checking employee uniqueness: %+v", err)
			return nil, err
		}

		updateBody["name"] = trimmed
	}

	if req.IsActive != nil {
		updateBody["is_active"] = *req.IsActive
	}

	if req.KandangIDs != nil {
		ids := normalizeKandangIDs(*req.KandangIDs)
		if len(ids) == 0 {
			return nil, fiber.NewError(fiber.StatusBadRequest, "kandang_ids must contain at least one valid id")
		}
		if err := s.ensureKandangIDsAccess(c, ids); err != nil {
			return nil, err
		}

		kandangIDs = ids
		needKandangUpdate = true
	}

	if len(updateBody) == 0 && !needKandangUpdate {
		return s.GetOne(c, id)
	}

	if err := s.Repository.DB().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
			}
		}

		if needKandangUpdate {
			if err := tx.WithContext(c.Context()).
				Where("employee_id = ?", id).
				Delete(&entity.EmployeeKandang{}).Error; err != nil {
				return err
			}

			relations := make([]entity.EmployeeKandang, 0, len(kandangIDs))
			for _, kandangID := range kandangIDs {
				relations = append(relations, entity.EmployeeKandang{
					EmployeeId: id,
					KandangId:  kandangID,
				})
			}

			if len(relations) > 0 {
				if err := tx.WithContext(c.Context()).Create(&relations).Error; err != nil {
					return err
				}
			}
		}

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

	return s.GetOne(c, id)
}

func (s employeesService) DeleteOne(c *fiber.Ctx, id uint) error {
	if err := s.ensureEmployeeAccess(c, 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, "Employees not found")
		}
		s.Log.Errorf("Failed to delete employees: %+v", err)
		return err
	}
	return nil
}

func normalizeKandangIDs(ids []uint) []uint {
	result := make([]uint, 0, len(ids))
	seen := make(map[uint]struct{})

	for _, id := range ids {
		if id == 0 {
			continue
		}

		if _, ok := seen[id]; ok {
			continue
		}

		seen[id] = struct{}{}
		result = append(result, id)
	}

	return result
}
