package activity

import (
	"context"
	"database/sql"
	"time"
)

type DrawConfig struct {
	PlayType        string
	DrawMode        string
	MinParticipants int64
	IntervalMinutes int64
	ScheduledTime   *time.Time
	RefundCouponID  int64
}

func (s *service) SaveActivityDrawConfig(ctx context.Context, activityID int64, cfg DrawConfig) error {
	st := sql.NullTime{}
	if cfg.ScheduledTime != nil {
		st = sql.NullTime{Time: cfg.ScheduledTime.UTC(), Valid: true}
	}
	return s.repo.GetDbW().Exec(
		"UPDATE activities SET play_type=?, draw_mode=?, min_participants=?, interval_minutes=?, scheduled_time=?, refund_coupon_id=? WHERE id=?",
		cfg.PlayType, cfg.DrawMode, cfg.MinParticipants, cfg.IntervalMinutes, st, cfg.RefundCouponID, activityID,
	).Error
}

func (s *service) GetActivityDrawConfig(ctx context.Context, activityID int64) (*DrawConfig, error) {
	var row struct {
		PlayType        string     `gorm:"column:play_type"`
		DrawMode        string     `gorm:"column:draw_mode"`
		MinParticipants int64      `gorm:"column:min_participants"`
		IntervalMinutes int64      `gorm:"column:interval_minutes"`
		ScheduledTime   *time.Time `gorm:"column:scheduled_time"`
		RefundCouponID  int64      `gorm:"column:refund_coupon_id"`
	}
	if err := s.repo.GetDbR().Raw("SELECT play_type, draw_mode, min_participants, interval_minutes, scheduled_time, refund_coupon_id FROM activities WHERE id=?", activityID).Scan(&row).Error; err != nil {
		return nil, err
	}
	return &DrawConfig{PlayType: row.PlayType, DrawMode: row.DrawMode, MinParticipants: row.MinParticipants, IntervalMinutes: row.IntervalMinutes, ScheduledTime: row.ScheduledTime, RefundCouponID: row.RefundCouponID}, nil
}
