package repository

import (
	"fmt"
	"strings"
	"web-qudo-be/app/database"
	"web-qudo-be/app/database/entity"
	"web-qudo-be/app/module/user_levels/request"
	"web-qudo-be/utils/paginator"
	utilSvc "web-qudo-be/utils/service"

	"github.com/google/uuid"
)

type userLevelsRepository struct {
	DB *database.Database
}

// UserLevelsRepository define interface of IUserLevelsRepository
type UserLevelsRepository interface {
	GetAll(clientId *uuid.UUID, req request.UserLevelsQueryRequest) (userLevelss []*entity.UserLevels, paging paginator.Pagination, err error)
	FindOne(clientId *uuid.UUID, id uint) (userLevels *entity.UserLevels, err error)
	FindOneByAlias(clientId *uuid.UUID, alias string) (userLevels *entity.UserLevels, err error)
	Create(clientId *uuid.UUID, userLevels *entity.UserLevels) (userLevelsReturn *entity.UserLevels, err error)
	Update(clientId *uuid.UUID, id uint, userLevels *entity.UserLevels) (err error)
	Delete(clientId *uuid.UUID, id uint) (err error)
}

func NewUserLevelsRepository(db *database.Database) UserLevelsRepository {
	return &userLevelsRepository{
		DB: db,
	}
}

// implement interface of IUserLevelsRepository
func (_i *userLevelsRepository) GetAll(clientId *uuid.UUID, req request.UserLevelsQueryRequest) (userLevelss []*entity.UserLevels, paging paginator.Pagination, err error) {
	var count int64

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

	// Filter by client_id if provided
	if clientId != nil {
		query = query.Where("client_id = ?", clientId)
	}

	if req.Name != nil && *req.Name != "" {
		name := strings.ToLower(*req.Name)
		query = query.Where("LOWER(name) LIKE ?", "%"+strings.ToLower(name)+"%")
	}
	if req.LevelNumber != nil {
		query = query.Where("level_number = ?", req.LevelNumber)
	}
	if req.ParentLevelId != nil {
		query = query.Where("parent_level_id = ?", req.ParentLevelId)
	}
	if req.ProvinceId != nil {
		query = query.Where("province_id = ?", req.ProvinceId)
	}
	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(&userLevelss).Error
	if err != nil {
		return
	}

	paging = *req.Pagination

	return
}

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

	return userLevels, nil
}

func (_i *userLevelsRepository) FindOneByAlias(clientId *uuid.UUID, alias string) (userLevels *entity.UserLevels, err error) {
	query := _i.DB.DB.Where("alias_name = ?", strings.ToLower(alias))
	if clientId != nil {
		query = query.Where("client_id = ?", clientId)
	}
	if err := query.First(&userLevels).Error; err != nil {
		return nil, err
	}

	return userLevels, nil
}

func (_i *userLevelsRepository) Create(clientId *uuid.UUID, userLevels *entity.UserLevels) (userLevelsReturn *entity.UserLevels, err error) {
	// Set client ID
	if clientId != nil {
		userLevels.ClientId = clientId
	}

	result := _i.DB.DB.Create(userLevels)
	return userLevels, result.Error
}

func (_i *userLevelsRepository) Update(clientId *uuid.UUID, id uint, userLevels *entity.UserLevels) (err error) {
	// Validate client access
	if clientId != nil {
		var count int64
		if err := _i.DB.DB.Model(&entity.UserLevels{}).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")
		}
	}

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

func (_i *userLevelsRepository) Delete(clientId *uuid.UUID, id uint) error {
	// Validate client access
	if clientId != nil {
		var count int64
		if err := _i.DB.DB.Model(&entity.UserLevels{}).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.UserLevels{}, id).Error
}
