package service

import (
	"errors"
	"fmt"
	"strings"

	"github.com/go-playground/validator/v10"
	"github.com/gofiber/fiber/v2"
	"github.com/sirupsen/logrus"
	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/suppliers/repositories"
	validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/suppliers/validations"
	"gitlab.com/mbugroup/lti-api.git/internal/utils"
	"gorm.io/gorm"
)

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

type supplierService struct {
	Log        *logrus.Logger
	Validate   *validator.Validate
	Repository repository.SupplierRepository
}

func NewSupplierService(repo repository.SupplierRepository, validate *validator.Validate) SupplierService {
	return &supplierService{
		Log:        utils.Log,
		Validate:   validate,
		Repository: repo,
	}
}

func (s supplierService) withRelations(db *gorm.DB) *gorm.DB {
	return db.
		Preload("CreatedUser").
		Preload("ProductSuppliers.Product.Uom").
		Preload("ProductSuppliers.Product.Flags").
		Preload("NonstockSuppliers.Nonstock.Uom").
		Preload("NonstockSuppliers.Nonstock.Flags")
}

func (s supplierService) withListRelations(db *gorm.DB) *gorm.DB {
	return db.Preload("CreatedUser")
}

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

	if params.Category != "" {
		category := strings.ToUpper(params.Category)
		if category != "BOP" && category != "SAPRONAK" {
			return nil, 0, fiber.NewError(fiber.StatusBadRequest, "Invalid supplier category")
		}
		params.Category = category
	}

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

	suppliers, total, err := s.Repository.GetAll(c.Context(), offset, params.Limit, func(db *gorm.DB) *gorm.DB {
		db = s.withListRelations(db)
		if params.Search != "" {
			return db.Where("name ILIKE ?", "%"+params.Search+"%")
		}

		if params.Category != "" {
			db = db.Where("category ILIKE ?", "%"+params.Category+"%")
		}

		if params.Flag != "" {
			flag := strings.ToUpper(params.Flag)
			db = db.Where(`
				EXISTS (
					SELECT 1
					FROM nonstock_suppliers nsup
					JOIN nonstocks n ON n.id = nsup.nonstock_id
					JOIN flags f ON f.flagable_id = n.id AND f.flagable_type = ?
					WHERE nsup.supplier_id = suppliers.id
					  AND UPPER(f.name) = ?
				)`,
				entity.FlagableTypeNonstock,
				flag,
			)
		}

		return db.Order("suppliers.created_at DESC").Order("suppliers.updated_at DESC")
	})

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

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

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

	if exists, err := s.Repository.AliasExists(c.Context(), strings.TrimSpace(strings.ToUpper(req.Alias)), nil); err != nil {
		s.Log.Errorf("Failed to check supplier alias: %+v", err)
		return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check supplier alias")
	} else if exists {
		return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Supplier with alias %s already exists", strings.TrimSpace(strings.ToUpper(req.Alias))))
	}

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

	category := strings.ToUpper(req.Category)
	if !utils.IsValidSupplierCategory(category) {
		return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid supplier category")
	}

	alias := strings.TrimSpace(strings.ToUpper(req.Alias))
	actorID, err := m.ActorIDFromContext(c)
	if err != nil {
		return nil, err
	}
	createBody := &entity.Supplier{
		Name:          req.Name,
		Alias:         alias,
		Pic:           req.Pic,
		Type:          typ,
		Category:      category,
		Hatchery:      req.Hatchery,
		Phone:         req.Phone,
		Email:         req.Email,
		Address:       req.Address,
		Npwp:          req.Npwp,
		AccountNumber: req.AccountNumber,
		DueDate:       req.DueDate,
		CreatedBy:     actorID,
	}

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

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

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

	if req.Alias != nil {
		if exists, err := s.Repository.AliasExists(c.Context(), strings.TrimSpace(strings.ToUpper(*req.Alias)), &id); err != nil {
			s.Log.Errorf("Failed to check supplier alias: %+v", err)
			return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check supplier alias")
		} else if exists {
			return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Supplier with alias %s already exists", strings.TrimSpace(strings.ToUpper(*req.Alias))))
		}
		updateBody["alias"] = strings.TrimSpace(strings.ToUpper(*req.Alias))
	}

	if req.Pic != nil {
		updateBody["pic"] = *req.Pic
	}

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

	if req.Category != nil {
		category := strings.ToUpper(*req.Category)
		if !utils.IsValidSupplierCategory(category) {
			return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid supplier category")
		}
		updateBody["category"] = category
	}

	if req.Hatchery != nil {
		updateBody["hatchery"] = *req.Hatchery
	}

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

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

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

	if req.Npwp != nil {
		updateBody["npwp"] = *req.Npwp
	}

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

	if req.DueDate != nil {
		updateBody["due_date"] = *req.DueDate
	}

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

	return s.GetOne(c, id)
}

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