package services

import (
	"errors"
	"gauth-central/internal/database"
	"gauth-central/internal/models"

	"gorm.io/gorm"
)

type TagService struct{}

func NewTagService() *TagService {
	return &TagService{}
}

// CreateTag creates a new tag
func (s *TagService) CreateTag(tagName string, isActive bool) (*models.Tag, error) {
	tag := models.Tag{
		Tag:      tagName,
		IsActive: isActive,
	}

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

	return &tag, nil
}

// GetAllTags retrieves all tags (optionally filter by active status)
func (s *TagService) GetAllTags(onlyActive bool) ([]models.Tag, error) {
	var tags []models.Tag
	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
}

// GetTagByID retrieves a tag by ID
func (s *TagService) GetTagByID(id string) (*models.Tag, error) {
	var tag models.Tag
	if err := database.DB.Where("id = ?", id).First(&tag).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("tag not found")
		}
		return nil, err
	}
	return &tag, nil
}

// UpdateTag updates an existing tag
func (s *TagService) UpdateTag(id string, tagName string, isActive *bool) (*models.Tag, error) {
	tag, err := s.GetTagByID(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
}

// DeleteTag deletes a tag
func (s *TagService) DeleteTag(id string) error {
	result := database.DB.Delete(&models.Tag{}, "id = ?", id)
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return errors.New("tag not found")
	}
	return nil
}
