package repository

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

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

// ArticleCommentsRepository define interface of IArticleCommentsRepository
type ArticleCommentsRepository interface {
	GetAll(clientId *uuid.UUID, req request.ArticleCommentsQueryRequest) (articleCommentss []*entity.ArticleComments, paging paginator.Pagination, err error)
	FindOne(clientId *uuid.UUID, id uint) (articleComments *entity.ArticleComments, err error)
	Create(clientId *uuid.UUID, articleComments *entity.ArticleComments) (articleCommentsReturn *entity.ArticleComments, err error)
	Update(clientId *uuid.UUID, id uint, articleComments *entity.ArticleComments) (err error)
	Delete(clientId *uuid.UUID, id uint) (err error)
}

func NewArticleCommentsRepository(db *database.Database, logger zerolog.Logger) ArticleCommentsRepository {
	return &articleCommentsRepository{
		DB:  db,
		Log: logger,
	}
}

// implement interface of IArticleCommentsRepository
func (_i *articleCommentsRepository) GetAll(clientId *uuid.UUID, req request.ArticleCommentsQueryRequest) (articleCommentss []*entity.ArticleComments, paging paginator.Pagination, err error) {
	var count int64

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

	// Add client filter
	if clientId != nil {
		query = query.Where("client_id = ?", clientId)
	}

	if req.Message != nil && *req.Message != "" {
		message := strings.ToLower(*req.Message)
		query = query.Where("LOWER(message) LIKE ?", "%"+strings.ToLower(message)+"%")
	}
	if req.ArticleId != nil {
		query = query.Where("article_id = ?", req.ArticleId)
	}
	if req.CommentFrom != nil {
		query = query.Where("comment_from = ?", req.CommentFrom)
	}
	if req.ParentId != nil {
		query = query.Where("parent_id = ?", req.ParentId)
	}
	if req.IsPublic != nil {
		query = query.Where("is_public = ?", req.IsPublic)
	}
	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(&articleCommentss).Error
	if err != nil {
		return
	}

	paging = *req.Pagination

	return
}

func (_i *articleCommentsRepository) FindOne(clientId *uuid.UUID, id uint) (articleComments *entity.ArticleComments, err error) {
	query := _i.DB.DB
	if clientId != nil {
		query = query.Where("client_id = ?", clientId)
	}
	if err := query.First(&articleComments, id).Error; err != nil {
		return nil, err
	}

	return articleComments, nil
}

func (_i *articleCommentsRepository) Create(clientId *uuid.UUID, articleComments *entity.ArticleComments) (articleCommentsReturn *entity.ArticleComments, err error) {
	// Set client ID
	if clientId != nil {
		articleComments.ClientId = clientId
	}
	result := _i.DB.DB.Create(articleComments)
	return articleComments, result.Error
}

func (_i *articleCommentsRepository) Update(clientId *uuid.UUID, id uint, articleComments *entity.ArticleComments) (err error) {
	// Validate client access
	if clientId != nil {
		var count int64
		if err := _i.DB.DB.Model(&entity.ArticleComments{}).Where("id = ? AND client_id = ?", id, clientId).Count(&count).Error; err != nil {
			return err
		}
		if count == 0 {
			return fmt.Errorf("access denied to this resource")
		}
	}

	articleCommentsMap, err := utilSvc.StructToMap(articleComments)
	if err != nil {
		return err
	}
	return _i.DB.DB.Model(&entity.ArticleComments{}).
		Where(&entity.ArticleComments{ID: id}).
		Updates(articleCommentsMap).Error
}

func (_i *articleCommentsRepository) Delete(clientId *uuid.UUID, id uint) error {
	// Validate client access
	if clientId != nil {
		var count int64
		if err := _i.DB.DB.Model(&entity.ArticleComments{}).Where("id = ? AND client_id = ?", id, clientId).Count(&count).Error; err != nil {
			return err
		}
		if count == 0 {
			return fmt.Errorf("access denied to this resource")
		}
	}

	return _i.DB.DB.Delete(&entity.ArticleComments{}, id).Error
}
