package service

import (
	"errors"
	"fmt"
	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/customers/repositories"
	validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/customers/validations"
	"gitlab.com/mbugroup/lti-api.git/internal/utils"
	"strings"

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

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

type customerService struct {
	Log        *logrus.Logger
	Validate   *validator.Validate
	Repository repository.CustomerRepository
}

func NewCustomerService(repo repository.CustomerRepository, validate *validator.Validate) CustomerService {
	return &customerService{
		Log:        utils.Log,
		Validate:   validate,
		Repository: repo,
	}
}

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

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

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

	customers, total, err := s.Repository.GetAll(c.Context(), offset, params.Limit, func(db *gorm.DB) *gorm.DB {
		db = s.withRelations(db)
		if params.Search != "" {
			db = db.Where("name ILIKE ?", "%"+params.Search+"%")
			if params.HasMarketing != nil && *params.HasMarketing {
				db = db.Where(`
					EXISTS (
						SELECT 1
						FROM marketings
						WHERE marketings.customer_id = customers.id
							AND marketings.deleted_at IS NULL
					)
				`)
			}
			return db
		}
		if params.HasMarketing != nil && *params.HasMarketing {
			db = db.Where(`
				EXISTS (
					SELECT 1
					FROM marketings
					WHERE marketings.customer_id = customers.id
						AND marketings.deleted_at IS NULL
				)
			`)
		}
		return db.Order("created_at DESC").Order("updated_at DESC")
	})

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

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

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

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

	typ := strings.ToUpper(req.Type)
	if !utils.IsValidCustomerSupplierType(typ) {
		return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid customer type")
	}

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

	createBody := &entity.Customer{
		Name:          req.Name,
		PicId:         req.PicId,
		Type:          typ,
		Address:       req.Address,
		Phone:         req.Phone,
		Email:         req.Email,
		AccountNumber: req.AccountNumber,
		CreatedBy:     actorID,
	}

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

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

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

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

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

	if req.Type != nil {
		typ := strings.ToUpper(*req.Type)
		if !utils.IsValidCustomerSupplierType(typ) {
			return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid customer type")
		}
		updateBody["type"] = typ
	}

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

	if req.Phone != nil {
		updateBody["phone"] = *req.Phone
	}

	if req.Email != nil {
		updateBody["email"] = *req.Email
	}

	if req.AccountNumber != nil {
		updateBody["account_number"] = *req.AccountNumber
	}

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

	return s.GetOne(c, id)
}

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