package services

import (
	"errors"

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

	"gorm.io/gorm"
)

type SiteSettingsService struct{}

func NewSiteSettingsService() *SiteSettingsService {
	return &SiteSettingsService{}
}

// CreateSiteSettings creates a new site settings entry.
func (s *SiteSettingsService) CreateSiteSettings(isActive bool, siteActive bool) (*models.SiteSettings, error) {
	settings := models.SiteSettings{
		IsActive:   isActive,
		SiteActive: siteActive,
	}

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

	return s.GetSiteSettingsByID(settings.ID.String())
}

// GetAllSiteSettings retrieves all site settings entries. Use onlyActive to filter public data.
func (s *SiteSettingsService) GetAllSiteSettings(onlyActive bool) ([]models.SiteSettings, error) {
	var settings []models.SiteSettings
	query := database.DB.Order("created_at desc")
	if onlyActive {
		query = query.Where("is_active = ?", true)
	}

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

	return settings, nil
}

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

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

// UpdateSiteSettings updates an existing site settings entry.
func (s *SiteSettingsService) UpdateSiteSettings(
	id string,
	isActive *bool,
	siteActive *bool,
) (*models.SiteSettings, error) {
	settings, err := s.GetSiteSettingsByID(id)
	if err != nil {
		return nil, err
	}

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

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

	return s.GetSiteSettingsByID(id)
}

// DeleteSiteSettings deletes a site settings entry by ID.
func (s *SiteSettingsService) DeleteSiteSettings(id string) error {
	result := database.DB.Delete(&models.SiteSettings{}, "id = ?", id)
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return errors.New("site settings not found")
	}
	return nil
}
