package repository

import (
	"fmt"
	"github.com/google/uuid"
	"github.com/rs/zerolog"
	"strings"
	"web-qudo-be/app/database"
	"web-qudo-be/app/database/entity"
	"web-qudo-be/app/module/clients/request"
	"web-qudo-be/utils/paginator"
)

type clientsRepository struct {
	DB  *database.Database
	Log zerolog.Logger
}

// ClientsRepository define interface of IClientsRepository
type ClientsRepository interface {
	GetAll(req request.ClientsQueryRequest) (clientss []*entity.Clients, paging paginator.Pagination, err error)
	FindOne(id uuid.UUID) (clients *entity.Clients, err error)
	Create(clients *entity.Clients) (clientsReturn *entity.Clients, err error)
	Update(id uuid.UUID, clients *entity.Clients) (err error)
	Delete(id uuid.UUID) (err error)
}

func NewClientsRepository(db *database.Database, logger zerolog.Logger) ClientsRepository {
	return &clientsRepository{
		DB:  db,
		Log: logger,
	}
}

// implement interface of IClientsRepository
func (_i *clientsRepository) GetAll(req request.ClientsQueryRequest) (clientss []*entity.Clients, paging paginator.Pagination, err error) {
	var count int64

	query := _i.DB.DB.Model(&entity.Clients{})
	query = query.Where("is_active = ?", true)

	if req.Name != nil && *req.Name != "" {
		name := strings.ToLower(*req.Name)
		query = query.Where("LOWER(name) LIKE ?", "%"+strings.ToLower(name)+"%")
	}
	if req.CreatedById != nil {
		query = query.Where("created_by_id = ?", req.CreatedById)
	}
	query.Count(&count)

	if req.Pagination.SortBy != "" {
		direction := "ASC"
		if req.Pagination.Sort == "desc" {
			direction = "DESC"
		}
		query.Order(fmt.Sprintf("%s %s", req.Pagination.SortBy, direction))
	}

	req.Pagination.Count = count
	req.Pagination = paginator.Paging(req.Pagination)

	err = query.Offset(req.Pagination.Offset).Limit(req.Pagination.Limit).Find(&clientss).Error
	if err != nil {
		return
	}

	paging = *req.Pagination

	return
}

func (_i *clientsRepository) FindOne(id uuid.UUID) (clients *entity.Clients, err error) {
	if err := _i.DB.DB.First(&clients, id).Error; err != nil {
		return nil, err
	}

	return clients, nil
}

func (_i *clientsRepository) Create(clients *entity.Clients) (clientsReturn *entity.Clients, err error) {
	result := _i.DB.DB.Create(clients)
	return clients, result.Error
}

func (_i *clientsRepository) Update(id uuid.UUID, clients *entity.Clients) (err error) {
	return _i.DB.DB.Model(&entity.Clients{}).
		Where(&entity.Clients{ID: id}).
		Updates(clients).Error
}

func (_i *clientsRepository) Delete(id uuid.UUID) error {
	return _i.DB.DB.Delete(&entity.Clients{}, id).Error
}
