package services


import (
	"errors"

	"gauth-central/internal/database"
	"gauth-central/internal/models"

	"gorm.io/gorm"
)

type PostTagService struct{}

func NewPostTagService() *PostTagService {
	return &PostTagService{}
}

func (s *PostTagService) CreatePostTag(tagName string, isActive bool) (*models.PostTag, error) {
	tag := models.PostTag{
		Tag:      tagName,
		IsActive: isActive,
	}

	if err := database.DB.Create(&tag).Error; err != nil {
		return nil, err
	}

	return &tag, nil
}

func (s *PostTagService) GetAllPostTags(onlyActive bool) ([]models.PostTag, error) {
	var tags []models.PostTag
	query := database.DB.Order("created_at desc")
	if onlyActive {
		query = query.Where("is_active = ?", true)
	}

	if err := query.Find(&tags).Error; err != nil {
		return nil, err
	}

	return tags, nil
}

func (s *PostTagService) GetPostTagByID(id string) (*models.PostTag, error) {
	var tag models.PostTag
	if err := database.DB.Where("id = ?", id).First(&tag).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("post tag not found")
		}
		return nil, err
	}
	return &tag, nil
}

func (s *PostTagService) UpdatePostTag(id string, tagName string, isActive *bool) (*models.PostTag, error) {
	tag, err := s.GetPostTagByID(id)
	if err != nil {
		return nil, err
	}

	updates := map[string]interface{}{}
	if tagName != "" {
		updates["tag"] = tagName
	}
	if isActive != nil {
		updates["is_active"] = *isActive
	}

	if err := database.DB.Model(tag).Updates(updates).Error; err != nil {
		return nil, err
	}

	return tag, nil
}

func (s *PostTagService) DeletePostTag(id string) error {
	result := database.DB.Delete(&models.PostTag{}, "id = ?", id)
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return errors.New("post tag not found")
	}
	return nil
}
