package repository

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

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

// ActivityLogsRepository define interface of IActivityLogsRepository
type ActivityLogsRepository interface {
	GetAll(clientId *uuid.UUID, req request.ActivityLogsQueryRequest) (activityLogss []*entity.ActivityLogs, paging paginator.Pagination, err error)
	FindOne(clientId *uuid.UUID, id uint) (activityLogs *entity.ActivityLogs, err error)
	Create(activityLogs *entity.ActivityLogs) (activityLogsReturn *entity.ActivityLogs, err error)
	Update(clientId *uuid.UUID, id uint, activityLogs *entity.ActivityLogs) (err error)
	Delete(clientId *uuid.UUID, id uint) (err error)
	CountUniqueVisitorAllTime(clientId *uuid.UUID) (count int64, err error)
	CountUniqueVisitorToday(clientId *uuid.UUID) (count int64, err error)
	CountTotalViewAllTime(clientId *uuid.UUID) (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(clientId *uuid.UUID, req request.ActivityLogsQueryRequest) (activityLogss []*entity.ActivityLogs, paging paginator.Pagination, err error) {
	var count int64

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

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

	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(clientId *uuid.UUID, id uint) (activityLogs *entity.ActivityLogs, err error) {
	query := _i.DB.DB.Where("id = ?", id)

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

	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(clientId *uuid.UUID, id uint, activityLogs *entity.ActivityLogs) (err error) {
	query := _i.DB.DB.Model(&entity.ActivityLogs{}).Where(&entity.ActivityLogs{ID: id})
	if clientId != nil {
		query = query.Where("client_id = ?", clientId)
	}
	return query.Updates(activityLogs).Error
}

func (_i *activityLogsRepository) Delete(clientId *uuid.UUID, id uint) error {
	query := _i.DB.DB.Model(&entity.ActivityLogs{}).Where("id = ?", id)
	if clientId != nil {
		query = query.Where("client_id = ?", clientId)
	}
	return query.Delete(&entity.ActivityLogs{}).Error
}

func (_i *activityLogsRepository) CountUniqueVisitorAllTime(clientId *uuid.UUID) (count int64, err error) {
	query := _i.DB.DB.Model(&entity.ActivityLogs{})
	if clientId != nil {
		query = query.Where("client_id = ?", clientId)
	}
	err = query.Distinct("visitor_ip").Count(&count).Error
	return
}

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

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

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