package repository

import (
	"fmt"
	"narasi-ahli-be/app/database"
	"narasi-ahli-be/app/database/entity/users"
	"narasi-ahli-be/app/module/users/request"
)

type UserExpertRepository interface {
	GetExperts(req request.UserExpertQueryRequest) ([]*users.Users, error)
	FindExpertByID(id uint) (*users.Users, error)
}

type userExpertRepository struct {
	DB *database.Database
}

func NewUserExpertRepository(db *database.Database) UserExpertRepository {
	return &userExpertRepository{DB: db}
}

func (r *userExpertRepository) GetExperts(
	req request.UserExpertQueryRequest,
) ([]*users.Users, error) {

	fmt.Println("=== GetExperts CALLED ===")
	fmt.Printf("repo instance: %+v\n", r)

	if r.DB == nil {
		panic("🔥 r.DB IS NIL")
	}

	if r.DB.DB == nil {
		panic("🔥 r.DB.DB IS NIL")
	}

	var res []*users.Users

	query := r.DB.DB.
	Debug(). // 🔥 TAMBAHKAN INI
	Model(&users.Users{}).
	Where(
		"user_role_id = ? AND (is_active = true OR is_active IS NULL)",
		3,
	)
	if req.Name != nil {
		query = query.Where("fullname ILIKE ?", "%"+*req.Name+"%")
	}

	if req.Type != nil {
		query = query.Where("type ILIKE ?", "%"+*req.Type+"%")
	}

	err := query.Find(&res).Error
	return res, err
}

func (r *userExpertRepository) FindExpertByID(id uint) (*users.Users, error) {
	var user users.Users
	err := r.DB.DB.
		Where(
			"id = ? AND user_role_id = ? AND (is_active = true OR is_active IS NULL)",
			id, 3,
		).
		First(&user).
		Error

	if err != nil {
		return nil, err
	}
	return &user, nil
}
