package repository

import (
	"narasi-ahli-be/app/database"
	"narasi-ahli-be/app/database/entity"
	"narasi-ahli-be/app/database/entity/user_agent"
)

type UserAgentRepository interface {
	ReplaceUserAgents(userID uint, agentIDs []uint) error
	GetAgentsByUser(userID uint) ([]entity.Agent, error)
	ValidateAgents(agentIDs []uint) ([]uint, error)

}

type userAgentRepository struct {
	DB *database.Database
}

func NewUserAgentRepository(db *database.Database) UserAgentRepository {
	return &userAgentRepository{DB: db}
}

func (r *userAgentRepository) ReplaceUserAgents(userID uint, agentIDs []uint) error {

	tx := r.DB.DB.Begin()

	if err := tx.Where("user_id = ?", userID).
		Delete(&user_agent.UserAgent{}).Error; err != nil {
		tx.Rollback()
		return err
	}

	if len(agentIDs) == 0 {
		return tx.Commit().Error
	}

	var mappings []user_agent.UserAgent
	for _, aid := range agentIDs {
		mappings = append(mappings, user_agent.UserAgent{
			UserID:  userID,
			AgentID: aid,
		})
	}

	if err := tx.Create(&mappings).Error; err != nil {
		tx.Rollback()
		return err
	}

	return tx.Commit().Error
}

func (r *userAgentRepository) GetAgentsByUser(userID uint) ([]entity.Agent, error) {
	var agents []entity.Agent

	err := r.DB.DB.
		Table("user_agents ua").
		Select("a.*").
		Joins("JOIN agents a ON a.id = ua.agent_id").
		Where("ua.user_id = ?", userID).
		Scan(&agents).Error

	return agents, err
}

func (r *userAgentRepository) ValidateAgents(agentIDs []uint) ([]uint, error) {
	var validIDs []uint

	err := r.DB.DB.
		Table("agents").
		Where("id IN ?", agentIDs).
		Pluck("id", &validIDs).Error

	return validIDs, err
}

