package repository

import (
	"context"

	"github.com/user-management-system/internal/domain"
	"gorm.io/gorm"
)

// WebhookRepository Webhook 持久化仓储
type WebhookRepository struct {
	db *gorm.DB
}

// NewWebhookRepository 创建 Webhook 仓储
func NewWebhookRepository(db *gorm.DB) *WebhookRepository {
	return &WebhookRepository{db: db}
}

// Create 创建 Webhook
func (r *WebhookRepository) Create(ctx context.Context, wh *domain.Webhook) error {
	// GORM omits zero values on insert for fields with DB defaults. Explicitly
	// backfill inactive status so repository callers can persist status=0.
	requestedStatus := wh.Status
	return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		if err := tx.Create(wh).Error; err != nil {
			return err
		}
		if requestedStatus == domain.WebhookStatusInactive {
			if err := tx.Model(&domain.Webhook{}).Where("id = ?", wh.ID).Update("status", requestedStatus).Error; err != nil {
				return err
			}
			wh.Status = requestedStatus
		}
		return nil
	})
}

// Update 更新 Webhook 字段（只更新 updates map 中的字段）
func (r *WebhookRepository) Update(ctx context.Context, id int64, updates map[string]interface{}) error {
	return r.db.WithContext(ctx).
		Model(&domain.Webhook{}).
		Where("id = ?", id).
		Updates(updates).Error
}

// Delete 删除 Webhook（软删除）
func (r *WebhookRepository) Delete(ctx context.Context, id int64) error {
	return r.db.WithContext(ctx).Delete(&domain.Webhook{}, id).Error
}

// GetByID 按 ID 获取 Webhook
func (r *WebhookRepository) GetByID(ctx context.Context, id int64) (*domain.Webhook, error) {
	var wh domain.Webhook
	err := r.db.WithContext(ctx).First(&wh, id).Error
	if err != nil {
		return nil, err
	}
	return &wh, nil
}

// ListByCreator 按创建者列出 Webhook（createdBy=0 表示列出所有）
func (r *WebhookRepository) ListByCreator(ctx context.Context, createdBy int64) ([]*domain.Webhook, error) {
	var webhooks []*domain.Webhook
	query := r.db.WithContext(ctx)
	if createdBy > 0 {
		query = query.Where("created_by = ?", createdBy)
	}
	if err := query.Find(&webhooks).Error; err != nil {
		return nil, err
	}
	return webhooks, nil
}

// ListByCreatorPaginated 按创建者分页列出 Webhook（createdBy=0 表示列出所有）
func (r *WebhookRepository) ListByCreatorPaginated(ctx context.Context, createdBy int64, offset, limit int) ([]*domain.Webhook, int64, error) {
	var webhooks []*domain.Webhook
	var total int64

	query := r.db.WithContext(ctx).Model(&domain.Webhook{})
	if createdBy > 0 {
		query = query.Where("created_by = ?", createdBy)
	}

	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	if offset > 0 {
		query = query.Offset(offset)
	}
	if limit > 0 {
		query = query.Limit(limit)
	}

	if err := query.Order("created_at DESC").Find(&webhooks).Error; err != nil {
		return nil, 0, err
	}

	return webhooks, total, nil
}

// ListActive 列出所有状态为活跃的 Webhook
func (r *WebhookRepository) ListActive(ctx context.Context) ([]*domain.Webhook, error) {
	var webhooks []*domain.Webhook
	err := r.db.WithContext(ctx).
		Where("status = ?", domain.WebhookStatusActive).
		Find(&webhooks).Error
	return webhooks, err
}

// CreateDelivery 记录投递日志
func (r *WebhookRepository) CreateDelivery(ctx context.Context, delivery *domain.WebhookDelivery) error {
	return r.db.WithContext(ctx).Create(delivery).Error
}

// ListDeliveries 按 Webhook ID 分页查询投递记录（最新在前）
func (r *WebhookRepository) ListDeliveries(ctx context.Context, webhookID int64, limit int) ([]*domain.WebhookDelivery, error) {
	var deliveries []*domain.WebhookDelivery
	err := r.db.WithContext(ctx).
		Where("webhook_id = ?", webhookID).
		Order("created_at DESC").
		Limit(limit).
		Find(&deliveries).Error
	return deliveries, err
}
