package repository

import (
	"context"

	"eslogad-be/internal/entities"

	"github.com/google/uuid"
	"gorm.io/gorm"
)

type UserRepositoryImpl struct {
	b *gorm.DB
}

func NewUserRepository(db *gorm.DB) *UserRepositoryImpl {
	return &UserRepositoryImpl{
		b: db,
	}
}

func (r *UserRepositoryImpl) Create(ctx context.Context, user *entities.User) error {
	return r.b.WithContext(ctx).Create(user).Error
}

func (r *UserRepositoryImpl) GetByID(ctx context.Context, id uuid.UUID) (*entities.User, error) {
	var user entities.User
	err := r.b.WithContext(ctx).
		Preload("Profile").
		Preload("Departments").
		First(&user, "id = ?", id).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}

func (r *UserRepositoryImpl) GetByEmail(ctx context.Context, email string) (*entities.User, error) {
	var user entities.User
	err := r.b.WithContext(ctx).
		Preload("Profile").
		Preload("Departments").
		Where("email = ?", email).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}

func (r *UserRepositoryImpl) GetByRole(ctx context.Context, role entities.UserRole) ([]*entities.User, error) {
	var users []*entities.User
	err := r.b.WithContext(ctx).Preload("Profile").Preload("Departments").Where("role = ?", role).Find(&users).Error
	return users, err
}

func (r *UserRepositoryImpl) GetActiveUsers(ctx context.Context, organizationID uuid.UUID) ([]*entities.User, error) {
	var users []*entities.User
	err := r.b.WithContext(ctx).
		Where(" is_active = ?", organizationID, true).
		Preload("Profile").
		Preload("Departments").
		Find(&users).Error
	return users, err
}

func (r *UserRepositoryImpl) Update(ctx context.Context, user *entities.User) error {
	return r.b.WithContext(ctx).Save(user).Error
}

func (r *UserRepositoryImpl) Delete(ctx context.Context, id uuid.UUID) error {
	return r.b.WithContext(ctx).Delete(&entities.User{}, "id = ?", id).Error
}

func (r *UserRepositoryImpl) UpdatePassword(ctx context.Context, id uuid.UUID, passwordHash string) error {
	return r.b.WithContext(ctx).Model(&entities.User{}).
		Where("id = ?", id).
		Update("password_hash", passwordHash).Error
}

func (r *UserRepositoryImpl) UpdateActiveStatus(ctx context.Context, id uuid.UUID, isActive bool) error {
	return r.b.WithContext(ctx).Model(&entities.User{}).
		Where("id = ?", id).
		Update("is_active", isActive).Error
}

func (r *UserRepositoryImpl) List(ctx context.Context, filters map[string]interface{}, limit, offset int) ([]*entities.User, int64, error) {
	var users []*entities.User
	var total int64

	query := r.b.WithContext(ctx).Model(&entities.User{})

	for key, value := range filters {
		query = query.Where(key+" = ?", value)
	}

	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	err := query.Limit(limit).Offset(offset).Preload("Profile").Preload("Departments").Find(&users).Error
	return users, total, err
}

func (r *UserRepositoryImpl) Count(ctx context.Context, filters map[string]interface{}) (int64, error) {
	var count int64
	query := r.b.WithContext(ctx).Model(&entities.User{})

	for key, value := range filters {
		query = query.Where(key+" = ?", value)
	}

	err := query.Count(&count).Error
	return count, err
}

// RBAC helpers
func (r *UserRepositoryImpl) GetRolesByUserID(ctx context.Context, userID uuid.UUID) ([]entities.Role, error) {
	var roles []entities.Role
	err := r.b.WithContext(ctx).
		Table("roles as r").
		Select("r.*").
		Joins("JOIN user_role ur ON ur.role_id = r.id AND ur.removed_at IS NULL").
		Where("ur.user_id = ?", userID).
		Find(&roles).Error
	return roles, err
}

func (r *UserRepositoryImpl) GetPermissionsByUserID(ctx context.Context, userID uuid.UUID) ([]entities.Permission, error) {
	var perms []entities.Permission
	err := r.b.WithContext(ctx).
		Table("permissions as p").
		Select("DISTINCT p.*").
		Joins("JOIN role_permissions rp ON rp.permission_id = p.id").
		Joins("JOIN user_role ur ON ur.role_id = rp.role_id AND ur.removed_at IS NULL").
		Where("ur.user_id = ?", userID).
		Find(&perms).Error
	return perms, err
}

func (r *UserRepositoryImpl) GetDepartmentsByUserID(ctx context.Context, userID uuid.UUID) ([]entities.Department, error) {
	var departments []entities.Department
	err := r.b.WithContext(ctx).
		Table("departments as d").
		Select("d.*").
		Joins("JOIN user_department ud ON ud.department_id = d.id AND ud.removed_at IS NULL").
		Where("ud.user_id = ?", userID).
		Find(&departments).Error
	return departments, err
}

func (r *UserRepositoryImpl) GetRolesByUserIDs(ctx context.Context, userIDs []uuid.UUID) (map[uuid.UUID][]entities.Role, error) {
	result := make(map[uuid.UUID][]entities.Role)
	if len(userIDs) == 0 {
		return result, nil
	}

	type row struct {
		UserID uuid.UUID
		RoleID uuid.UUID
		Name   string
		Code   string
	}

	var rows []row
	err := r.b.WithContext(ctx).
		Table("user_role as ur").
		Select("ur.user_id, r.id as role_id, r.name, r.code").
		Joins("JOIN roles r ON r.id = ur.role_id").
		Where("ur.removed_at IS NULL AND ur.user_id IN ?", userIDs).
		Scan(&rows).Error
	if err != nil {
		return nil, err
	}
	for _, rw := range rows {
		role := entities.Role{ID: rw.RoleID, Name: rw.Name, Code: rw.Code}
		result[rw.UserID] = append(result[rw.UserID], role)
	}
	return result, nil
}

func (r *UserRepositoryImpl) ListWithFilters(ctx context.Context, search *string, roleCode *string, isActive *bool, limit, offset int) ([]*entities.User, int64, error) {
	var users []*entities.User
	var total int64

	q := r.b.WithContext(ctx).Table("users").Model(&entities.User{})
	if search != nil && *search != "" {
		like := "%" + *search + "%"
		q = q.Where("users.name ILIKE ?", like)
	}
	if isActive != nil {
		q = q.Where("users.is_active = ?", *isActive)
	}
	if roleCode != nil && *roleCode != "" {
		q = q.Joins("JOIN user_role ur ON ur.user_id = users.id AND ur.removed_at IS NULL").
			Joins("JOIN roles r ON r.id = ur.role_id").
			Where("r.code = ?", *roleCode)
	}

	if err := q.Distinct("users.id").Count(&total).Error; err != nil {
		return nil, 0, err
	}

	if err := q.Select("users.*").Distinct("users.id").Limit(limit).Offset(offset).Preload("Profile").Preload("Departments").Find(&users).Error; err != nil {
		return nil, 0, err
	}
	return users, total, nil
}
