package services

import (
	"errors"

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

	"gorm.io/gorm"
)

type ServiceTitleService struct{}

func NewServiceTitleService() *ServiceTitleService {
	return &ServiceTitleService{}
}

// CreateServiceTitle creates a new service title entry.
func (s *ServiceTitleService) CreateServiceTitle(title string, titleSub string, isActive bool) (*models.ServiceTitle, error) {
	item := models.ServiceTitle{
		Title:    title,
		TitleSub: titleSub,
		IsActive: isActive,
	}

	err := database.DB.Transaction(func(tx *gorm.DB) error {
		if isActive {
			// Deactivate all other service titles
			if err := tx.Model(&models.ServiceTitle{}).Where("is_active = ?", true).Update("is_active", false).Error; err != nil {
				return err
			}
		}
		if err := tx.Create(&item).Error; err != nil {
			return err
		}
		return nil
	})

	if err != nil {
		return nil, err
	}

	return s.GetServiceTitleByID(item.ID.String())
}

// GetAllServiceTitles retrieves all service titles. Use onlyActive to filter public data.
func (s *ServiceTitleService) GetAllServiceTitles(onlyActive bool) ([]models.ServiceTitle, error) {
	var items []models.ServiceTitle
	query := database.DB.Order("created_at desc")
	if onlyActive {
		query = query.Where("is_active = ?", true)
	}

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

	return items, nil
}

// GetFirstActiveServiceTitle returns the newest active service title entry.
func (s *ServiceTitleService) GetFirstActiveServiceTitle() (*models.ServiceTitle, error) {
	var item models.ServiceTitle
	if err := database.DB.Where("is_active = ?", true).Order("created_at desc").First(&item).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("service title not found")
		}
		return nil, err
	}
	return &item, nil
}

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

// UpdateServiceTitle updates an existing service title entry.
func (s *ServiceTitleService) UpdateServiceTitle(id string, title *string, titleSub *string, isActive *bool) (*models.ServiceTitle, error) {
	item, err := s.GetServiceTitleByID(id)
	if err != nil {
		return nil, err
	}

	updates := map[string]interface{}{}
	if title != nil {
		updates["title"] = *title
	}
	if titleSub != nil {
		updates["title_sub"] = *titleSub
	}
	if isActive != nil {
		updates["is_active"] = *isActive
	}

	if len(updates) > 0 {
		err := database.DB.Transaction(func(tx *gorm.DB) error {
			if isActive != nil && *isActive {
				// Deactivate all other service titles except the current one
				if err := tx.Model(&models.ServiceTitle{}).Where("id != ? AND is_active = ?", id, true).Update("is_active", false).Error; err != nil {
					return err
				}
			}
			if err := tx.Model(item).Updates(updates).Error; err != nil {
				return err
			}
			return nil
		})
		if err != nil {
			return nil, err
		}
	}

	return s.GetServiceTitleByID(id)
}

// DeleteServiceTitle deletes a service title by ID.
func (s *ServiceTitleService) DeleteServiceTitle(id string) error {
	result := database.DB.Delete(&models.ServiceTitle{}, "id = ?", id)
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return errors.New("service title not found")
	}
	return nil
}
