package repository

import (
	"git.mchus.pro/mchus/quoteforge/internal/models"
	"gorm.io/gorm"
)

type AlertRepository struct {
	db *gorm.DB
}

func NewAlertRepository(db *gorm.DB) *AlertRepository {
	return &AlertRepository{db: db}
}

func (r *AlertRepository) Create(alert *models.PricingAlert) error {
	return r.db.Create(alert).Error
}

func (r *AlertRepository) GetByID(id uint) (*models.PricingAlert, error) {
	var alert models.PricingAlert
	err := r.db.First(&alert, id).Error
	if err != nil {
		return nil, err
	}
	return &alert, nil
}

func (r *AlertRepository) Update(alert *models.PricingAlert) error {
	return r.db.Save(alert).Error
}

type AlertFilter struct {
	Status   models.AlertStatus
	Severity models.AlertSeverity
	Type     models.AlertType
	LotName  string
}

func (r *AlertRepository) List(filter AlertFilter, offset, limit int) ([]models.PricingAlert, int64, error) {
	var alerts []models.PricingAlert
	var total int64

	query := r.db.Model(&models.PricingAlert{})

	if filter.Status != "" {
		query = query.Where("status = ?", filter.Status)
	}
	if filter.Severity != "" {
		query = query.Where("severity = ?", filter.Severity)
	}
	if filter.Type != "" {
		query = query.Where("alert_type = ?", filter.Type)
	}
	if filter.LotName != "" {
		query = query.Where("lot_name = ?", filter.LotName)
	}

	query.Count(&total)

	err := query.
		Order("FIELD(severity, 'critical', 'high', 'medium', 'low')").
		Order("created_at DESC").
		Offset(offset).
		Limit(limit).
		Find(&alerts).Error

	return alerts, total, err
}

func (r *AlertRepository) CountByStatus(status models.AlertStatus) (int64, error) {
	var count int64
	err := r.db.Model(&models.PricingAlert{}).
		Where("status = ?", status).
		Count(&count).Error
	return count, err
}

func (r *AlertRepository) UpdateStatus(id uint, status models.AlertStatus) error {
	return r.db.Model(&models.PricingAlert{}).
		Where("id = ?", id).
		Update("status", status).Error
}

func (r *AlertRepository) ExistsByLotAndType(lotName string, alertType models.AlertType) (bool, error) {
	var count int64
	err := r.db.Model(&models.PricingAlert{}).
		Where("lot_name = ? AND alert_type = ? AND status IN ('new', 'acknowledged')", lotName, alertType).
		Count(&count).Error
	return count > 0, err
}
