package services

import (
	"errors"
	"time"

	"fotbal-club/internal/models"

	"gorm.io/gorm"
)

type SetupService struct {
	db *gorm.DB
}

func NewSetupService(db *gorm.DB) *SetupService {
	return &SetupService{db: db}
}

// GetSetupStatus returns the current setup status
func (s *SetupService) GetSetupStatus() (*models.SetupInfo, error) {
	var setupInfo models.SetupInfo
	if err := s.db.FirstOrCreate(&setupInfo, models.SetupInfo{Model: gorm.Model{ID: 1}}).Error; err != nil {
		return nil, err
	}
	return &setupInfo, nil
}

// MarkSMTPConfigured marks the SMTP configuration as completed
func (s *SetupService) MarkSMTPConfigured() error {
	return s.db.Model(&models.SetupInfo{}).Where("id = ?", 1).Updates(map[string]interface{}{
		"smtp_configured": true,
		"updated_at":      time.Now(),
	}).Error
}

// SaveClubInfo saves the club information from FACR
func (s *SetupService) SaveClubInfo(clubInfo *models.ClubInfo) error {
	// Start a transaction
	tx := s.db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// Update setup info
	if err := tx.Model(&models.SetupInfo{}).Where("id = ?", 1).Updates(map[string]interface{}{
		"club_imported": true,
		"updated_at":    time.Now(),
	}).Error; err != nil {
		tx.Rollback()
		return err
	}

	// Save club info
	clubInfo.SetupInfoID = 1
	if err := tx.Create(clubInfo).Error; err != nil {
		tx.Rollback()
		return err
	}

	return tx.Commit().Error
}

// CompleteSetup marks the setup as completed
func (s *SetupService) CompleteSetup() error {
	now := time.Now()
	return s.db.Model(&models.SetupInfo{}).Where("id = ?", 1).Updates(map[string]interface{}{
		"status":       models.SetupStatusCompleted,
		"completed_at": now,
		"updated_at":   now,
	}).Error
}

// SkipSetup marks the setup as skipped
func (s *SetupService) SkipSetup() error {
	now := time.Now()
	return s.db.Model(&models.SetupInfo{}).Where("id = ?", 1).Updates(map[string]interface{}{
		"status":     models.SetupStatusSkipped,
		"skipped_at": now,
		"updated_at": now,
	}).Error
}

// GetClubInfo returns the club information if it exists
func (s *SetupService) GetClubInfo() (*models.ClubInfo, error) {
	var clubInfo models.ClubInfo
	if err := s.db.Where("setup_info_id = ?", 1).First(&clubInfo).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		return nil, err
	}
	return &clubInfo, nil
}
