package repository

import (
	"jaecoo-be/app/database"
	"jaecoo-be/app/database/entity"
	"jaecoo-be/app/module/sales_agents/request"
	"jaecoo-be/utils/paginator"
	"strings"

	"github.com/rs/zerolog"
)

type salesAgentsRepository struct {
	DB  *database.Database
	Log zerolog.Logger
}

type SalesAgentsRepository interface {
	GetAll(req request.SalesAgentsQueryRequest) (agents []*entity.SalesAgents, paging paginator.Pagination, err error)
	FindOne(id uint) (agent *entity.SalesAgents, err error)
	Create(agent *entity.SalesAgents) (agentReturn *entity.SalesAgents, err error)
	Update(id uint, agent *entity.SalesAgents) (err error)
	Delete(id uint) (err error)
	FindByProfilePicturePath(profilePicturePath string) (agent *entity.SalesAgents, err error)
}

func NewSalesAgentsRepository(db *database.Database, log zerolog.Logger) SalesAgentsRepository {
	return &salesAgentsRepository{
		DB:  db,
		Log: log,
	}
}

func (_i *salesAgentsRepository) GetAll(req request.SalesAgentsQueryRequest) (agents []*entity.SalesAgents, paging paginator.Pagination, err error) {
	var count int64

	query := _i.DB.DB.Model(&entity.SalesAgents{})

	if req.Name != nil && *req.Name != "" {
		name := strings.ToLower(*req.Name)
		query = query.Where("LOWER(name) LIKE ?", "%"+name+"%")
	}

	if req.JobTitle != nil && *req.JobTitle != "" {
		query = query.Where("job_title = ?", *req.JobTitle)
	}

	if req.AgentType != nil && *req.AgentType != "" {
		query = query.Where("agent_type LIKE ?", "%"+*req.AgentType+"%")
	}

	query = query.Where("is_active = ?", true)

	query.Count(&count)

	req.Pagination.Count = count
	req.Pagination = paginator.Paging(req.Pagination)

	query = query.Order("created_at DESC")

	err = query.Offset(req.Pagination.Offset).Limit(req.Pagination.Limit).Find(&agents).Error
	if err != nil {
		return
	}

	paging = *req.Pagination

	return
}

func (_i *salesAgentsRepository) FindOne(id uint) (agent *entity.SalesAgents, err error) {
	agent = &entity.SalesAgents{}
	err = _i.DB.DB.Where("id = ? AND is_active = ?", id, true).First(agent).Error
	return
}

func (_i *salesAgentsRepository) Create(agent *entity.SalesAgents) (agentReturn *entity.SalesAgents, err error) {
	if err = _i.DB.DB.Create(agent).Error; err != nil {
		return
	}
	agentReturn = agent
	return
}

func (_i *salesAgentsRepository) Update(id uint, agent *entity.SalesAgents) (err error) {
	err = _i.DB.DB.Model(&entity.SalesAgents{}).Where("id = ?", id).Updates(agent).Error
	return
}

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

func (_i *salesAgentsRepository) FindByProfilePicturePath(profilePicturePath string) (agent *entity.SalesAgents, err error) {
	agent = &entity.SalesAgents{}
	err = _i.DB.DB.Where("profile_picture_path LIKE ? AND is_active = ?", "%"+profilePicturePath, true).First(agent).Error
	return
}

