package service

import (
	"errors"
	"fmt"

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

type bankService struct {
	Log        *logrus.Logger
	Validate   *validator.Validate
	Repository repository.BankRepository
}

func NewBankService(repo repository.BankRepository, validate *validator.Validate) BankService {
	return &bankService{
		Log:        utils.Log,
		Validate:   validate,
		Repository: repo,
	}
}

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

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

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

	banks, 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 ILIKE ?", "%"+params.Search+"%")
		}
		return db.Order("created_at DESC").Order("updated_at DESC")
	})

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

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

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

	if exists, err := s.Repository.AccountNumberExists(c.Context(), req.AccountNumber, nil); err != nil {
		s.Log.Errorf("Failed to check bank account number: %+v", err)
		return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check bank account number")
	} else if exists {
		return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Bank with account number %s already exists", req.AccountNumber))
	}

	createBody := &entity.Bank{
		Name:          req.Name,
		Alias:         req.Alias,
		Owner:         req.Owner,
		AccountNumber: req.AccountNumber,
		CreatedBy:     1,
	}

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

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

func (s bankService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.Bank, 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 bank name: %+v", err)
			return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check bank name")
		} else if exists {
			return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Bank with name %s already exists", *req.Name))
		}
		updateBody["name"] = *req.Name
	}
	if req.Alias != nil {
		updateBody["alias"] = *req.Alias
	}
	if req.Owner != nil {
		updateBody["owner"] = *req.Owner
	}
	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, "Bank not found")
		}
		s.Log.Errorf("Failed to update bank: %+v", err)
		return nil, err
	}

	return s.GetOne(c, id)
}

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