package repository

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

type agentRepository struct {
	DB *database.Database
}

type AgentRepository interface {
	GetAll(req request.AgentQueryRequest) ([]*entity.Agent, error)
	FindById(id uint) (*entity.Agent, error)
	Create(agent *entity.Agent) (*entity.Agent, error)
	Update(id uint, data map[string]interface{}) error
	Delete(id uint) error

	FindByAgentId(agentId string) (*entity.Agent, error)

}

func NewAgentRepository(db *database.Database) AgentRepository {
	return &agentRepository{DB: db}
}

func (_i *agentRepository) GetAll(req request.AgentQueryRequest) (agents []*entity.Agent, err error) {
	query := _i.DB.DB.Model(&entity.Agent{}).
		Where("is_active = ?", true)

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

	err = query.Order("created_at DESC").Find(&agents).Error
	return
}

func (_i *agentRepository) FindById(id uint) (*entity.Agent, error) {
	var agent entity.Agent
	err := _i.DB.DB.Where("id = ? AND is_active = ?", id, true).
		First(&agent).Error
	if err != nil {
		return nil, err
	}
	return &agent, nil
}

func (_i *agentRepository) FindByAgentId(agentId string) (*entity.Agent, error) {
	var agent entity.Agent
	err := _i.DB.DB.Where("agent_id = ? ", agentId).
		First(&agent).Error
	if err != nil {
		return nil, err
	}
	return &agent, nil
}

func (_i *agentRepository) Create(agent *entity.Agent) (*entity.Agent, error) {
	if err := _i.DB.DB.Create(agent).Error; err != nil {
		return nil, err
	}
	return agent, nil
}

func (_i *agentRepository) Update(id uint, data map[string]interface{}) error {
	return _i.DB.DB.Model(&entity.Agent{}).
		Where("id = ?", id).
		Updates(data).Error
}

func (_i *agentRepository) Delete(id uint) error {
	return _i.DB.DB.Model(&entity.Agent{}).
		Where("id = ?", id).
		Update("is_active", false).Error
}
