package repository

import (
	"fmt"
	"jaecoo-be/app/database"
	"jaecoo-be/app/database/entity"
	"jaecoo-be/app/module/activity_logs/request"
	"jaecoo-be/utils/paginator"
	"strings"
	"time"

	"github.com/rs/zerolog"
)

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

// ActivityLogsRepository define interface of IActivityLogsRepository
type ActivityLogsRepository interface {
	GetAll(req request.ActivityLogsQueryRequest) (activityLogss []*entity.ActivityLogs, paging paginator.Pagination, err error)
	FindOne(id uint) (activityLogs *entity.ActivityLogs, err error)
	Create(activityLogs *entity.ActivityLogs) (activityLogsReturn *entity.ActivityLogs, err error)
	Update(id uint, activityLogs *entity.ActivityLogs) (err error)
	Delete(id uint) (err error)
	CountUniqueVisitorAllTime() (count int64, err error)
	CountUniqueVisitorToday() (count int64, err error)
	CountTotalViewAllTime() (count int64, err error)
}

func NewActivityLogsRepository(db *database.Database, logger zerolog.Logger) ActivityLogsRepository {
	return &activityLogsRepository{
		DB:  db,
		Log: logger,
	}
}

// implement interface of IActivityLogsRepository
func (_i *activityLogsRepository) GetAll(req request.ActivityLogsQueryRequest) (activityLogss []*entity.ActivityLogs, paging paginator.Pagination, err error) {
	var count int64

	query := _i.DB.DB.Model(&entity.ActivityLogs{})

	if req.ActivityTypeId != nil {
		query = query.Where("activity_type_id = ?", req.ActivityTypeId)
	}
	if req.Url != nil && *req.Url != "" {
		url := strings.ToLower(*req.Url)
		query = query.Where("LOWER(url) LIKE ?", "%"+strings.ToLower(url)+"%")
	}
	if req.ArticleId != nil {
		query = query.Where("article_id = ?", req.ArticleId)
	}
	if req.UserId != nil {
		query = query.Where("user_id = ?", req.UserId)
	}
	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(&activityLogss).Error
	if err != nil {
		return
	}

	paging = *req.Pagination

	return
}

func (_i *activityLogsRepository) FindOne(id uint) (activityLogs *entity.ActivityLogs, err error) {
	query := _i.DB.DB.Where("id = ?", id)

	if err := query.First(&activityLogs).Error; err != nil {
		return nil, err
	}

	return activityLogs, nil
}

func (_i *activityLogsRepository) Create(activityLogs *entity.ActivityLogs) (activityLogsReturn *entity.ActivityLogs, err error) {
	result := _i.DB.DB.Create(activityLogs)
	return activityLogs, result.Error
}

func (_i *activityLogsRepository) Update(id uint, activityLogs *entity.ActivityLogs) (err error) {
	query := _i.DB.DB.Model(&entity.ActivityLogs{}).Where(&entity.ActivityLogs{ID: id})
	return query.Updates(activityLogs).Error
}

func (_i *activityLogsRepository) Delete(id uint) error {
	query := _i.DB.DB.Model(&entity.ActivityLogs{}).Where("id = ?", id)
	return query.Delete(&entity.ActivityLogs{}).Error
}

func (_i *activityLogsRepository) CountUniqueVisitorAllTime() (count int64, err error) {
	query := _i.DB.DB.Model(&entity.ActivityLogs{})
	err = query.Distinct("visitor_ip").Count(&count).Error
	return
}

func (_i *activityLogsRepository) CountTotalViewAllTime() (count int64, err error) {
	query := _i.DB.DB.Model(&entity.ActivityLogs{}).Where("activity_type_id = ?", 2)
	err = query.Count(&count).Error
	return
}

func (_i *activityLogsRepository) CountUniqueVisitorToday() (count int64, err error) {
	tenMinutesAgo := time.Now().Add(-10 * time.Minute)

	query := _i.DB.DB.Model(&entity.AuditTrails{}).Where("created_at >= ?", tenMinutesAgo)
	err = query.Select("ip").Group("ip").Count(&count).Error
	return
}
